Skip to content

Commit 9e646ac

Browse files
SimplifyPath : Accepted
1 parent 05c2076 commit 9e646ac

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ My accepted leetcode solutions to some of the common interview problems.
160160
- [Excel Sheet Column Number](problems/src/string/ExcelSheetColumnNumber.java) (Easy)
161161
- [Compare Version Numbers](problems/src/string/CompareVersionNumbers.java) (Easy)
162162
- [Valid Palindrome](problems/src/string/ValidPalindrome.java) (Easy)
163+
- [Simplify Path](problems/src/string/SimplifyPath.java) (Medium)
163164

164165

165166
#### [Tree](problems/src/tree)
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package string;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Deque;
5+
import java.util.StringTokenizer;
6+
7+
/**
8+
* Created by gouthamvidyapradhan on 28/07/2017.
9+
*
10+
* Given an absolute path for a file (Unix-style), simplify it.
11+
12+
For example,
13+
path = "/home/", => "/home"
14+
path = "/a/./b/../../c/", => "/c"
15+
16+
Corner Cases:
17+
Did you consider the case where path = "/../"?
18+
In this case, you should return "/".
19+
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
20+
In this case, you should ignore redundant slashes and return "/home/foo".
21+
*/
22+
public class SimplifyPath {
23+
/**
24+
* Main method
25+
* @param args
26+
* @throws Exception
27+
*/
28+
public static void main(String[] args) throws Exception{
29+
System.out.println(new SimplifyPath().simplifyPath("/home/"));
30+
}
31+
32+
public String simplifyPath(String path) {
33+
if(path == null || path.isEmpty()) return "/";
34+
StringTokenizer st = new StringTokenizer(path, "/");
35+
Deque<String> dQueue = new ArrayDeque<>();
36+
while(st.hasMoreTokens()){
37+
String token = st.nextToken();
38+
if(token.trim().equals("..")){
39+
if(!dQueue.isEmpty())
40+
dQueue.pop();
41+
} else if(token.trim().equals(".")){
42+
//ignore
43+
}
44+
else dQueue.push(token);
45+
}
46+
if(dQueue.isEmpty()) return "/";
47+
StringBuilder finalStr = new StringBuilder();
48+
while(!dQueue.isEmpty()){
49+
finalStr.append("/").append(dQueue.removeLast());
50+
}
51+
return finalStr.toString();
52+
}
53+
54+
55+
}

0 commit comments

Comments
 (0)