Skip to content

Commit d6ba042

Browse files
committed
add solution of problem 71: simplify path
1 parent 105b00e commit d6ba042

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

SimplifyPath71/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Given an absolute path for a file (Unix-style), simplify it.
2+
3+
For example,
4+
**path** = "/home/", => "/home"
5+
**path** = "/a/./b/../../c/", => "/c"

SimplifyPath71/Solution.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class Solution {
2+
public String simplifyPath(String path) {
3+
if (path == null)
4+
return "/";
5+
6+
Stack<String> stack = new Stack<String>();
7+
stack.push("/");
8+
9+
String[] pathArray = path.split("/");
10+
11+
for (int i = 0; i < pathArray.length; i++) {
12+
if (pathArray[i].equals(".") || pathArray[i].equals("")) {
13+
//do nothing
14+
} else if (pathArray[i].equals("..")) {
15+
if (!stack.peek().equals("/"))
16+
stack.pop();
17+
} else {
18+
stack.push(pathArray[i]);
19+
}
20+
}
21+
22+
StringBuilder sb = new StringBuilder();
23+
for (String s : stack) {
24+
sb.append(s);
25+
if (!s.equals("/"))
26+
sb.append("/");
27+
}
28+
29+
String result = sb.toString();
30+
return result.length() > 1 ? result.substring(0, result.length() - 1) : result;
31+
}
32+
}

0 commit comments

Comments
 (0)