原题链接:71. Simplify Path
欢迎优化!
【思路】
本题考查字符串和栈的基本操作。本身并不难:
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String temp = "";
for (int i = 0; i < path.length(); i++) {
while (i < path.length() && path.charAt(i++) == '/') //跳过'/'
i++;
while (i < path.length() && path.charAt(i) != '/') { //将文件名记录在temp中
temp += path.charAt(i);
i++;
}
if (temp.equals("..") && !stack.isEmpty()) //如果为"..",且栈不空,弹出第一个(返回上一级目录)
stack.pop();
else if (!temp.equals(".") && !temp.equals("..") && !temp.equals("")) //入栈
stack.add(temp);
temp = "";
}
while (!stack.isEmpty())
temp = "/" + stack.pop() + temp;
return temp == "" ? "/" : temp;
}
252 / 252
test cases passed. Runtime: 11 ms Your runtime beats 63.37% of javasubmissions.
欢迎优化!
本文深入探讨了简化路径问题,通过栈的基本操作实现路径简化。详细解释了算法逻辑,包括跳过分隔符、记录文件名及处理特殊指令,最终得到简化后的路径。
3756

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



