Java for LeetCode 071 Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
解题思路:
首先要了解linux目录的意思,请参考Linux的文件管理
先把path按" /" split,建立一个栈,如果出现..则出栈,否则入栈,最后输出这个栈即可,JAVA实现如下:
public String simplifyPath(String path) {
Stack<String> res = new Stack<String>();
String[] ps = path.split("/");
for (String a : ps) {
if (a.equals("..")) {
if (!res.empty())
res.pop();
}
else if (a.equals(".") || a.equals(""))
continue;
else
res.push(a);
}
if (res.empty())
return "/";
StringBuilder sb = new StringBuilder();
while(!res.empty())
sb.append("/" + res.get(i));
return sb.toString();
}

浙公网安备 33010602011771号