Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
只需要设置对/.. /. 和 / 的判断即可
public class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
Set<String> set = new HashSet<String>();
set.add(".");
set.add("..");
set.add("");
for(String s : path.split("/")){
if(s.equals("..")&& !stack.isEmpty()){
stack.pop();
}else if(!set.contains(s)) stack.push(s);
}
String res = "";
while(!stack.isEmpty()){
res = "/" + stack.pop() + res;
}
return res.isEmpty() ? "/" : res;
}
}