71. 简化路径
2025-02-27 14:48:04

Problem: 71. 简化路径

思路

本题应该要想到用来解决。因为问题的关键在于..上一级目录的处理,需要取消掉上一个保存的元素,这样自然可以想到后到先出的栈结构。

另外一点是分词的处理。对于路径,我们需要提取路径中按/分隔的所有字符组。实际上Java的String类有split的操作,我们只需要按照/分词即可。如果不用split,那么我们遇到/时跳过,并用Stringbuilder也可以达到相同的效果。

同样,Java也有join操作,可以简化拼接的代码量。

Code

[]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public String simplifyPath(String path) {
int q = 0;
int n = path.length();
char[] cs = path.toCharArray();
//Java String有Split操作和join操作
Deque<String> stack = new ArrayDeque<>();
while (q < n) {
StringBuilder sb = new StringBuilder();
if (cs[q] == '/') {
q++;
continue;
}
while (q < n && cs[q] != '/') {
sb.append(cs[q]);
q++;
}
String s = sb.toString();
if (s.isEmpty()) {
continue;
}
if ("..".equals(s)) {
if (!stack.isEmpty()) stack.pop();
}
else if (!".".equals(s)) {
stack.push(s);
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()) {
sb.append('/');
sb.append(stack.pollLast());
}
String ans = sb.toString();
if (ans.isEmpty()) {
ans = "/";
}
return ans;
}
}