Skip to content

Commit a2eacc2

Browse files
committed
simplify unix path
1 parent 09ddf68 commit a2eacc2

2 files changed

Lines changed: 89 additions & 0 deletions

File tree

PuzzleCoding/src/BSTtoDLL.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,11 @@ public static ArrayList<Node> bstToDLL(Node node) {
9191
return dll;
9292
}
9393

94+
95+
9496
static Node prev, head;
9597

98+
// in place approach
9699
public static void bstToDllinPlace(Node p) {
97100
if (p == null)
98101
return;
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import java.util.Stack;
2+
3+
/**
4+
*
5+
* Given an absolute path for a file (Unix-style), simplify it.
6+
7+
For example,
8+
path = "/home/", => "/home"
9+
path = "/a/./b/../../c/", => "/c"
10+
Corner Cases:
11+
Did you consider the case where path = "/../"?
12+
In this case, you should return "/".
13+
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
14+
In this case, you should ignore redundant slashes and return "/home/foo".
15+
16+
*/
17+
public class SimplifyUnixPath {
18+
public static void main(String[] args){
19+
20+
String s1 = "//../";
21+
System.out.println(simplifyUnixPath(s1));
22+
23+
String s2 = "/a/./.b//../c/";
24+
System.out.println(simplifyUnixPath(s2));
25+
26+
String s3 = "/home/of/foo/../../bar/../is/.//here/.";
27+
System.out.println(simplifyUnixPath(s3));
28+
29+
String s4 = "/home/of/foo/../";
30+
System.out.println(simplifyUnixPath(s4));
31+
32+
}
33+
34+
public static String simplifyUnixPath(String path){
35+
Stack<String> pathStack = new Stack<String>();
36+
String dir = "";
37+
38+
for(int i =0; i<path.length(); i++){
39+
char c = path.charAt(i);
40+
if(c != '/'){
41+
dir += c;
42+
continue;
43+
}
44+
// only "/"
45+
if(dir.length() == 0)
46+
continue;
47+
if(dir.charAt(0) == '.'){
48+
if(dir.length() >1){
49+
if(dir.charAt(1) == '.'){
50+
// dir /..ab/
51+
if(dir.length()>2){
52+
pathStack.push(dir);
53+
}
54+
else {
55+
// dir /../
56+
if(pathStack.size()>0){
57+
pathStack.pop();
58+
}
59+
}
60+
}
61+
else {
62+
// dir /.ab/
63+
pathStack.push(dir);
64+
}
65+
}
66+
// current path, do nothing
67+
}
68+
else { // one dir
69+
pathStack.push(dir);
70+
}
71+
72+
// clear dir for next one
73+
dir = "";
74+
}
75+
76+
String finalPath = "";
77+
for(int i =0; i < pathStack.size();i++){
78+
finalPath += "/" + pathStack.get(i);
79+
}
80+
if(pathStack.size() == 0)
81+
finalPath = "/";
82+
83+
return finalPath;
84+
85+
}
86+
}

0 commit comments

Comments
 (0)