LeetCode071——简化路径
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/simplify-path/description/
题目描述:
知识点:栈
思路:利用栈实现路径简化
明确路径的含义:
"./"表示当前路径。"../"表示上一级目录。"/"表示下一级目录。"../../"表示上上一级目录。
首先对字符串path按"/"做一个分割处理,得到一个字符串数组strings。
对于strings中的字符串,如果是".",则跳过。如果是"..",如果此时stack不为空,则弹出栈顶元素。如果不是".",也不是"..",也不是"",则入栈。
遍历完strings数组后,保存结果。如果result结果为空,需要返回"/"。否则,直接返回result即可。
时间复杂度和空间复杂度均是O(n),其中n为path中"/"的数量。
JAVA代码:
public class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
String[] strings = path.split("/");
for (int i = 0; i < strings.length; i++) {
if (".".equals(strings[i])) {
continue;
} else if ("..".equals(strings[i])) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!"".equals(strings[i])) {
stack.push(strings[i]);
}
}
String result = "";
while(!stack.isEmpty()) {
result = "/" + stack.pop() + result;
}
return result.equals("") ? "/" : result;
}
}
LeetCode解题报告: