-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSimplifyPath.java
55 lines (48 loc) · 1.83 KB
/
SimplifyPath.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
43
44
45
46
47
48
49
50
51
52
53
54
55
// https://leetcode.com/problems/simplify-path
// T: O(|path|)
// S: O(|path|)
import java.util.LinkedList;
public class SimplifyPath {
private static final char SLASH = '/';
private static final String ROOT = "/";
private static final String GO_ONE_LEVEL_UP = "..";
private static final String STAY_WHERE_YOU_ARE = ".";
public String simplifyPath(String path) {
final LinkedList<StringBuilder> fragments = new LinkedList<>();
StringBuilder current = new StringBuilder();
for (int i = 0 ; i < path.length() ; i++) {
if (path.charAt(i) == SLASH) {
if (!isEmpty(current)) {
addToFragments(current, fragments);
current = new StringBuilder();
}
} else current.append(path.charAt(i));
}
if (!isEmpty(current)) addToFragments(current, fragments);
return toPath(fragments);
}
private String toPath(LinkedList<StringBuilder> fragments) {
if (fragments.isEmpty()) return ROOT;
StringBuilder result = new StringBuilder();
for (StringBuilder fragment : fragments) {
result.append(SLASH).append(fragment);
}
return result.toString();
}
private void removeLast(LinkedList<StringBuilder> fragments) {
if (!fragments.isEmpty()) {
fragments.removeLast();
}
}
private void addToFragments(StringBuilder current, LinkedList<StringBuilder> fragments) {
String currentString = current.toString();
if (GO_ONE_LEVEL_UP.equals(currentString)) {
removeLast(fragments);
} else if (!STAY_WHERE_YOU_ARE.equals(currentString)) {
fragments.add(current);
}
}
private boolean isEmpty(StringBuilder stringBuilder) {
return stringBuilder.length() == 0;
}
}