-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimplifyPath.java
36 lines (35 loc) · 1.02 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
import java.util.ArrayList;
public class Solution {
public String simplifyPath(String path) {
int start = 1;
ArrayList<String> parts = new ArrayList<String>();
while (start < path.length()) {
if (path.charAt(start) == '/') {
start++;
continue;
}
int pos = path.indexOf('/', start);
if (pos < 0) {
pos = path.length();
}
String part = path.substring(start, pos);
start = pos;
if (part.equals("."))
continue;
else if (part.equals("..")) {
if (parts.size() > 0)
parts.remove(parts.size() - 1);
}
else
parts.add(part);
}
if (parts.size() == 0)
return "/";
StringBuffer sb = new StringBuffer();
for (String part : parts) {
sb.append('/');
sb.append(part);
}
return sb.toString();
}
}