forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplifypath.java
More file actions
executable file
·45 lines (39 loc) · 1.22 KB
/
simplifypath.java
File metadata and controls
executable file
·45 lines (39 loc) · 1.22 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
40
41
42
43
44
45
public class Solution {
public String simplifyPath(String path) {
// Start typing your Java solution below
// DO NOT write main() function
if(path.length()==1) return path;
path = path.replaceAll("/$","");
path = path.replaceAll("/+","/");
if(path.length()==1) return path;
Stack<String> s = new Stack<String>();
while(path.length()!=0){
int index = path.indexOf('/');
if(index==-1) index = path.length();
if(index==0) {
path = path.substring(1);
continue;
}
String tmp = path.substring(0,index);
if(index!=path.length()){
path = path.substring(index+1);
}else{
path = "";
}
if(tmp.equals(".")){
}else if(tmp.equals("..")){
if(!s.empty()){
s.pop();
}
}else{
s.push(tmp);
}
}
String ans = "";
while(!s.empty()){
ans = "/" + s.pop() + ans;
}
if(ans.length()==0) ans = "/";
return ans;
}
}