71. Simplify Path

Stack

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
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
int n = path.length();
int i = 0;

while (i < n) {
// skip multiple '/'
while (i < n && path.charAt(i) == '/') {
i++;
}
if (i >= n) break;

// extract the path name
int start = i;
while (i < n && path.charAt(i) != '/') {
i++;
}
String part = path.substring(start, i);

// process the path name
if (part.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!part.equals(".") && !part.isEmpty()) {
stack.push(part);
}
}

// construct the result
if (stack.isEmpty()) return "/";

StringBuilder result = new StringBuilder();
for (String dir : stack) {
result.append("/").append(dir);
}

return result.toString();
}
}

Remarks:

  1. TC: $O(n)$, SC: $O(n)$.