-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathSimiplifyPaths.java
More file actions
35 lines (30 loc) · 797 Bytes
/
SimiplifyPaths.java
File metadata and controls
35 lines (30 loc) · 797 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
30
31
32
33
34
35
class Solution {
// TC : O(n)
// SC : O(n)
public String simplifyPath(String path) {
Stack<String> st = new Stack<>();
String[] pathList = path.split("\\/");
for(String p : pathList){
if(p.length() == 0 || p.equals(".")){
continue;
} else if(p.equals("..")){
if(!st.empty()){
st.pop();
}
} else {
// string case
st.push(p);
}
}
// StringBuilder
String ans = "";
while(!st.empty()){
ans =st.pop() +"/"+ ans;
}
if(ans.length() == 0){
return "/";
}else{
return "/" + ans.substring(0, ans.length() -1);
}
}
}