-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplifyPath.java
More file actions
29 lines (26 loc) · 798 Bytes
/
SimplifyPath.java
File metadata and controls
29 lines (26 loc) · 798 Bytes
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
package leetcode.string.simplifypath;
import java.util.LinkedList;
// 02/22/2015
public class SimplifyPath {
// assumption: absolute path (start from '/')
public String simplifyPath(String path) {
LinkedList<String> stack = new LinkedList<String>();
String[] pathsplit = path.split("/");
for (String p : pathsplit) {
if (p.equals("..") && !stack.isEmpty()) { // stack pop
stack.removeLast();
} else if (p.length() != 0 && !p.equals(".") && !p.equals("..")) {
stack.addLast(p); // stack push
} // other cases: do nothing
}
StringBuilder sb = new StringBuilder();
if (stack.isEmpty())
return "/"; // !!! corner case
for (String p : stack) { // build output
sb.append("/");
sb.append(p);
}
return sb.toString();
}
}
//String path = "/home/../hadoop/";