-
Notifications
You must be signed in to change notification settings - Fork 20
/
SimplifyPath.java
45 lines (39 loc) · 1.23 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
import java.util.Stack;
/**
* Given an absolute path for a file (Unix-style), simplify it.
* <p>
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
* <p>
* Corner Cases:
* Did you consider the case where path = "/../"?
* In this case, you should return "/".
* Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
* In this case, you should ignore redundant slashes and return "/home/foo".
* <p>
* Accepted.
*/
public class SimplifyPath {
public String simplifyPath(String path) {
if (path == null || path.isEmpty()) {
return path;
}
String[] strings = path.split("/");
Stack<String> stack = new Stack<>();
for (int i = 1; i < strings.length; i++) {
if (strings[i].equals("..")) {
if (!stack.empty()) {
stack.pop();
}
} else if (!strings[i].equals(".") && !strings[i].isEmpty()) {
stack.push(strings[i]);
}
}
StringBuilder sb = new StringBuilder();
stack.forEach(s ->
sb.append("/").append(s)
);
return sb.length() == 0 ? "/" : sb.toString();
}
}