-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0071-simplify-path.java
38 lines (30 loc) · 978 Bytes
/
0071-simplify-path.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
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
StringBuilder curr = new StringBuilder();
String newPath = path + "/";
for(int i=0;i<newPath.length();i++) {
char ch = newPath.charAt(i);
if(ch == '/') {
if(curr.toString().equals("..")) {
if(!stack.isEmpty()) {
stack.pop();
}
} else if(!curr.isEmpty() && !curr.toString().equals(".")) {
stack.push(curr.toString());
}
curr = new StringBuilder();
} else {
curr.append(ch);
}
}
curr = new StringBuilder();
while(!stack.isEmpty()) {
curr.insert(0, "/" + stack.pop());
}
if(curr.length() == 0) {
curr.append('/');
}
return curr.toString();
}
}