题目
一开始想着用类似于split("\s+")这种的,发现没有,那就单个"/"划分吧,把空格的地方后期处理一下就行。因为StringBuilder的reverse是整个每个字符串都要翻转,所以要用到两个Stack
class Solution {
public String simplifyPath(String path) {
String[] str = path.split("/");
Stack<String> stack = new Stack<>();
for(int i=0;i<str.length;i++){
if(str[i].length()==0 || str[i].equals(".")){
continue;
}else if(str[i].equals("..")){
if(!stack.isEmpty()) stack.pop();
}else{
stack.push(str[i]);
}
}
if(stack.isEmpty()) return "/";
StringBuilder sb = new StringBuilder();
Stack<String> stack1 = new Stack<>();
while(!stack.isEmpty()){
stack1.push(stack.pop());
}
while(!stack1.isEmpty()){
sb.append("/");
sb.append(stack1.pop());
}
return sb.toString();
}
}