-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimlifyPath.java
50 lines (46 loc) · 1.17 KB
/
SimlifyPath.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
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.Stack;
/**
*
* @author chenqun
* Given an absolute path for a file (Unix-style), simplify it.
* For example,path = "/home/", => "/home",path = "/a/./b/../../c/", => "/c"
*/
public class SimlifyPath {
public String simplyfypath(String path){
String ans = "";
Stack<String> stack = new Stack<String>();
//È¥³ýpathÖÐÖظ´µÄ/
String newpath = "";
for(int i=1; i<path.length(); i++){
if(path.charAt(i) == path.charAt(i-1) && path.charAt(i-1) == '/')
continue;
else
newpath += path.charAt(i);
}
String[] cat = newpath.split("/");
for(int i=0; i<cat.length; i++){
if(cat[i].equals("..")){
if(!stack.isEmpty())
stack.pop();
else
//return "/";
continue;
}else if(cat[i].equals("."))
continue;
else {
stack.push(cat[i]);
}
}
if(stack.isEmpty()) return "/";
while(!stack.isEmpty()){
ans = '/' + stack.pop() + ans;
}
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SimlifyPath test = new SimlifyPath();
String path = "/a/./b///../c/../././../d/..//../e/./f/./g/././//.//h///././/..///";
System.out.println("ans " + test.simplyfypath(path));
}
}