这个题只要搞清楚什么是unix的path格式就好 就是后面没有/ 除了字母等有意义的字符以外 只有..有用 就是向上的意思
所以用stack 不是..也不是无用的就push 遇到..就pop
最后把stack里面的连起来 注意corner case 就是stack为空 但是遇到了。。 无法pop
但是也要忽略。。
public class Solution {
public String simplifyPath(String path) {
if ( path == null || path.length() == 0 )
return "";
Stack <String> stack = new Stack <String> ();
for ( String str : path.split("/") ){
if ( str.equals("") || str.equals(".") || ( stack.isEmpty() && str.equals("..") ))
continue;
else if ( !stack.isEmpty() && str.equals("..") )
stack.pop();
else
stack.push( str );
}
if ( stack.isEmpty () )
return "/";
String res = "";
while ( !stack.isEmpty() ){
res = "/" + stack.pop() + res;
}
return res;
}
}