这个题只要搞清楚什么是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;
}
}

本文详细解释了如何通过栈操作来简化Unix路径,利用栈来处理路径中的特殊符号,如'..'和'.',实现路径的高效压缩。
209

被折叠的 条评论
为什么被折叠?



