Skip to content

Commit 6b833b6

Browse files
committed
Add Stacks folder and 71_Simplify_Path.java
1 parent d3c528a commit 6b833b6

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Stacks/71_Simplify_Path.java

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

0 commit comments

Comments
 (0)