leetcode_071

Simplify Path


Problem

简化路径

Solution

用了两个 stack 来解决
其实可以用 Deque

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
41
42
43
44
45
46
47
public class {
public String simplifyPath(String path) {
String[] strs = path.split("/");
Stack<String> stack = new Stack<>();
String back = "..";
String cur = ".";
for(String str : strs) {
if(str.equals(back)){
if(!stack.isEmpty()) {
stack.pop();
}
continue;
}
// "." 或者 "" 不变
if(str.equals(cur) || str.equals("")){
continue;
}
// 其他路劲则是入栈
stack.push(str);
}
if(stack.isEmpty()){
return "/";
} else {
// 反转stack
Stack<String> stack1 = new Stack<>();
while(!stack.isEmpty()){
stack1.push(stack.pop());
}
stack = stack1;
// 此时栈顶为根目录
StringBuilder sb = new StringBuilder("/");
while(!stack.isEmpty()){
sb.append(stack.pop());
sb.append("/");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}
}

Over!