题目出处
题目描述
个人解法
思路:
todo
代码示例:(Java)
todo
复杂度分析
todo
官方解法
方法1:栈
思路:
代码示例:(Java)
public class Solution1 {
public String simplifyPath(String path) {
String[] names = path.split("/");
Deque<String> stack = new ArrayDeque<String>();
for (String name : names) {
if ("..".equals(name)) {
if (!stack.isEmpty()) {
stack.pollLast();
}
} else if (name.length() > 0 && !".".equals(name)) {
stack.offerLast(name);
}
}
StringBuffer ans = new StringBuffer();
if (stack.isEmpty()) {
ans.append('/');
} else {
while (!stack.isEmpty()) {
ans.append('/');
ans.append(stack.pollFirst());
}
}
return ans.toString();
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是字符串 path 的长度。
- 空间复杂度:O(n)。我们需要 O(n) 的空间存储 names 中的所有字符串。