Skip to content

Commit 3cd8c92

Browse files
committed
Simplify Path
1 parent 3518e16 commit 3cd8c92

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

SimplifyPath.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import java.util.LinkedList;
2+
import java.util.List;
3+
4+
/**
5+
* Given an absolute path for a file (Unix-style), simplify it.
6+
*
7+
* For example,
8+
*
9+
* path = "/home/", => "/home"
10+
* path = "/a/./b/../../c/", => "/c"
11+
*
12+
* click to show corner cases.
13+
*
14+
* Corner Cases:
15+
* Did you consider the case where path = "/../"?
16+
* In this case, you should return "/".
17+
* Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
18+
* In this case, you should ignore redundant slashes and return "/home/foo".
19+
*
20+
*/
21+
22+
public class SimplifyPath {
23+
public String simplifyPath(String path) {
24+
int length = path.length();
25+
if (length == 0)
26+
return path;
27+
List<String> dicts = new LinkedList<String>();
28+
int slow = 0;
29+
int fast = 0;
30+
while (true) {
31+
while (slow < length && path.charAt(slow) == '/') {
32+
slow++;
33+
}
34+
if (slow >= length)
35+
break;
36+
fast = slow;
37+
while (fast < length && path.charAt(fast) != '/') {
38+
fast++;
39+
}
40+
String s = path.substring(slow, fast);
41+
if (s.equals("..")) {
42+
if (!dicts.isEmpty()) {
43+
dicts.remove(dicts.size() - 1);
44+
}
45+
} else if (!s.equals(".")) {
46+
dicts.add(s);
47+
}
48+
slow = fast;
49+
}
50+
StringBuffer ret = new StringBuffer();
51+
for (String s : dicts) {
52+
ret.append('/');
53+
ret.append(s);
54+
}
55+
return ret.length() == 0 ? "/" : ret.toString();
56+
}
57+
}

0 commit comments

Comments
 (0)