class Solution {
public String simplifyPath(String path) {
StringBuilder sb = new StringBuilder();
Stack<String> stack = new Stack<>();
String pre = "..", curr = ".";
//char lastc = ' ';
String[] paths = path.split("/");
for(int i = 0; i < paths.length; i++){
if(pre.equals(paths[i]) ){
if(!stack.empty()){
stack.pop();
}
}
else if(curr.equals(paths[i]) || "".equals(paths[i])){
continue;
}
else {
stack.push(paths[i]);
}
}
for(int i = 0; i < stack.size(); i++){
sb.append("/");
sb.append(stack.get(i));
}
if("".equals(sb.toString())){
return "/";
}
return sb.toString();
}
}
网友评论