题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
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"
.
题目要求按Unix的路径格式简化路径。查阅Unix的规则知道:
1)根目录是/;
2)..表示返回上级目录
3).表示当前目录,可以忽略
4)/表示路径的分隔符,连续的多条/等价于一个/
5)如果不是在根目录,结尾处不需要/
有了上述规则,就很容易知道用栈来实现,用一个方法获取两个/之间的内容,如果是字母字符串,就进栈,如果为..,就pop(当然要非空),如果为.或者是空字符,就忽略。更新指针到下一个/。
import java.util.Stack;
public class No71_SimplifyPath {
public static void main(String[] args){
System.out.println(simplifyPath("/home//foo/"));
}
public static String simplifyPath(String path) {
Stack<String> stk = new Stack<String>();
int index = 0;
while(index < path.length()){
int end = index+1;
if(path.charAt(index) == '/'){
while(end<path.length() && path.charAt(end) != '/') end++;
String tmp = path.substring(index+1, end);
if(tmp.equals("..")){
if(!stk.empty()) stk.pop();
}
else if(!tmp.equals(".") && !tmp.equals("")){
stk.push(tmp);
}
index = end;
}
}
if(stk.empty()) return "/";
String ret = "";
while(!stk.empty()){
ret = "/"+stk.pop()+ret;
}
return ret;
}
}