-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimplifyPath.java
34 lines (27 loc) · 940 Bytes
/
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
package Stacks;
import java.util.*;
public class SimplifyPath {
public static String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
String[] tokens = path.split("/+ ");
for (int i=0; i<tokens.length; i++){
if (stack.size() > 0 && stack.peek() == "..") {
stack.pop();
}else if (!stack.isEmpty() && (stack.peek() == "." || stack.peek() == "")){
continue;
}
stack.push(tokens[i]);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
String ans = sb.reverse().toString();
if (sb.length() == 0) return "/";
else return ans;
}
public static void main(String[] args) {
String path = "/home//foo/";
System.out.println(simplifyPath(path));
}
}