题目:
给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
例如,
path = “/home/”, => “/home”
path = “/a/./b/…/…/c/”, => “/c”
边界情况:
你是否考虑了 路径 = “/…/” 的情况?
在这种情况下,你需返回 “/” 。
此外,路径中也可能包含多个斜杠 ‘/’ ,如 “/home//foo/” 。
在这种情况下,你可忽略多余的斜杠,返回 “/home/foo” 。
分析:
使用两个栈
代码:
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
path = path.replace("//", "/");
if (path.endsWith("/"))
path = path.substring(0, path.length() - 1);
String[] ss = path.split("/");
for (String s : ss) {
if (s.equals(".") || s.equals("")) {
continue;
} else if (s.equals("..")) {
if (!stack.isEmpty())
stack.pop();
} else {
stack.push(s);
}
}
StringBuilder res = new StringBuilder();
Stack<String> temp = new Stack<String>();
while (!stack.isEmpty())
temp.push(stack.pop());
while (!temp.isEmpty())
res.append("/" + temp.pop());
if (res.length() == 0) {
res.append("/");
}
return res.toString();
}
效率:
总结:
使用栈,效率有待优化