forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplifyPath.java
More file actions
52 lines (45 loc) · 948 Bytes
/
SimplifyPath.java
File metadata and controls
52 lines (45 loc) · 948 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Stack;
public class Solution {
public String simplifyPath(String path) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<String> stack = new Stack<String>();
int len = path.length();
if(len==1) return "/";
int i=0;
int j=1;
while(j<len){
if(path.charAt(j) == '/'){
if(j-i > 1){
String temp = path.substring(i+1, j);
if(temp.equals("..")){
if(!stack.isEmpty())
stack.pop();
}
else if(!temp.equals("."))
stack.push(temp);
}
i=j;
}
j++;
}
if(i<len-1){
String temp = path.substring(i+1);
if(temp.equals("..")){
if(!stack.isEmpty())
stack.pop();
}
else if(!temp.equals("."))
stack.push(temp);
}
if(stack.isEmpty())
return "/";
else{
String s = "";
while(!stack.isEmpty()){
s = "/"+stack.pop()+s;
}
return s;
}
}
}