Poison

71. Simplify Path

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
class Solution {
public String simplifyPath(String path) {
Deque<String> deque = new LinkedList<>();
for (String str : path.split("/")) {
switch (str) {
case ".":
case "":
// ignore
break;
case "..":
if (!deque.isEmpty()) {
deque.removeLast();
}
break;
default:
deque.addLast(str);
}
}

if (deque.isEmpty()) {
return "/";
} else {
StringBuilder sb = new StringBuilder();
for (String str : deque) {
sb.append("/").append(str);
}
return sb.toString();
}
}
}
Reference

71. Simplify Path