Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
Corner Cases:
Did you consider the case where path = “/../”?
In this case, you should return “/”.
Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”.
In this case, you should ignore redundant slashes and return “/home/foo”.
public String simplifyPath(String path) {
Stack<String> result = new Stack<String>();
for(int i = 0;i < path.length();){
int j = i+1;
while(j < path.length() && path.charAt(j) != '/')
j++;
//System.out.println(path.substring(i,j));
if(path.substring(i,j).equals("/")) ;
else if(path.substring(i,j).equals("/.")) ;
else if(path.substring(i,j).equals("/..")){
if(!result.empty())
result.pop();
}
else{
result.push(path.substring(i,j));
}
i = j;
}
if(result.empty())
return "/";
StringBuffer temp = new StringBuffer();
for(String str:result) temp.append(str);
return temp.toString();
}
教师里讨论问题真的很。。。。