题目
按照linux的方式简化 路径字符串
代码
public class Solution {
public String simplifyPath(String path) {
if(path == null){
return null;
}
LinkedList<String> stack =new LinkedList<String>();
String temp = new String();
int i =0;
int n = path.length();
while(i<n){
if(path.charAt(i)!='/')
break;
i++;
}
while(i<n){
char cur = path.charAt(i);
if(cur!='/'){
temp+=cur;
}
else{
if(temp.equals("..")){
if(!stack.isEmpty()){
stack.pop();
}
}
else if(temp.length()>0 && !temp.equals(".")){
stack.push(new String(temp));
}
temp = new String();
}
i++;
}
if(temp.length()>0){
if(temp.equals("..")){
if(!stack.isEmpty()){
stack.pop();
}
}
else if(!temp.equals(".")){
stack.push(new String(temp));
}
}
StringBuffer ans = new StringBuffer();
while(!stack.isEmpty()){
StringBuffer sb = new StringBuffer(stack.pop()).reverse();
ans= ans.append(sb).append("/");
}
if(ans.length()==0){
return "/";
}
return new String(ans.reverse());
}
}
思路
1 考虑用栈来做
2 注意corner,比如 .. . ///
3 可以用split()来简化写法。