forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplifyPath.java
More file actions
39 lines (39 loc) · 1.21 KB
/
SimplifyPath.java
File metadata and controls
39 lines (39 loc) · 1.21 KB
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
//O(N)
public class Solution {
public String simplifyPath(String path) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<String> st = new Stack<String>();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < path.length(); ++i){
char a = path.charAt(i);
if(a == '/'){
if(sb.length() > 0 && !sb.toString().equals("."))
st.push(sb.toString());
sb = new StringBuffer();
}
else if(a == '.'){
if(!sb.toString().equals("."))
sb.append('.');
else if(!st.isEmpty()){
sb = new StringBuffer();
st.pop();
}
}
else{
sb.append(a);
}
}
if(sb.length() > 0 && !sb.toString().equals("."))
st.push(sb.toString());
if(st.isEmpty())
return "/";
else{
String result = "";
while(!st.isEmpty()){
result = "/" + st.pop() + result;
}
return result;
}
}
}