For example,
path =
"/home/"
, => "/home"
path =
"/a/./b/../../c/"
, => "/c"
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"
.题目就这些case,其实没有说清楚是遇到"/../"其实只退一层,遇到"."也不退,只是不显示这一层而已,用stack就可以解决这题
用"/"可以把string 分成很多份,如果最后是空的,就返回"/"
public String simplifyPath(String path) {
String[] res = path.split("/");
Stack st = new Stack();
for(String s:res){
if(s.equals(".")==true||s.equals("")==true){
;
}
else if(s.equals("..") == true){
if(st.empty() == false)
st.pop();
}
else{
st.push(s);
}
}
String tes = "";
while(st.empty() == false){
tes = "/" + st.pop() + tes;
}
if(tes.length() == 0)
tes = "/";
return tes;
}