-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPathHelper.java
42 lines (35 loc) · 1010 Bytes
/
PathHelper.java
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
package org.sean.stack;
import java.util.ArrayDeque;
import java.util.Deque;
/***
* 71. Simplify Path
*/
public class PathHelper {
public String simplifyPath(String path) {
if (path.equals("/"))
return path;
String[] segments = path.split("\\/+");
Deque<String> stack = new ArrayDeque<>();
for (String segment : segments) {
if (segment.equals(".")) {
// No-Op
} else if (segment.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else {
if (!segment.isEmpty())
stack.push(segment);
}
}
StringBuilder builder = new StringBuilder();
while (!stack.isEmpty()) {
builder.insert(0, '/');
builder.insert(1, stack.pop());
}
if (builder.length() == 0) {
builder.append('/');
}
return builder.toString();
}
}