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"
.
好吧,这道题超出我的范围了,不了解这路径的规则啊。
首先要科普一下,/. 表示当前目录,就是不动 /..表示返回上一级目录,如果没有上一级,也不动 /...这个没什么效果,跟普通的一样
首先要split("/") 用一个栈保存即可,如果正常的话入栈,/. 不动 /...出栈即可 代码如下~
public class Solution {
public String simplifyPath(String path) {
String[] words = path.split("/");
Stack<String> st = new Stack<String>();
for(String word : words){
switch(word){
case("") :
case(".") : break;
case("..") : if(!st.isEmpty())st.pop();
break;
default : if(!st.isEmpty())st.push("/"+word);
else st.push(word);
}
}
if(st.isEmpty()){
return "/";
}else{
StringBuilder sb = new StringBuilder("");
while(!st.isEmpty()){
sb.insert(0, st.pop());
}
return "/"+sb.toString();
}
}
}