Problem Description
Thoughts
- 把path
split
成一个个子路径 - 使用一个
stack
遍历所有的路径- 当子路径为
.
和空时,不进栈 - 当子路径为
..
时,pop出上一层路径
- 当子路径为
- 最后再从
bottom
到top
遍历栈,把路径拼装回去
public String simplifyPath(String path) {
String[]paths = path.split("/");
Stack<String> s = new Stack<String>();
for(String dir : paths) {
if(dir.equals(".") || dir.isEmpty())
continue;
if(dir.equals("..")) {
if(!s.isEmpty())
s.pop();
}
else
s.push(dir);
}
StringBuilder res = new StringBuilder();
for(String dir : s) {
res.append("/");
res.append(dir);
}
return res.length() == 0 ? "/" : res.toString();
}