Skip to content

Commit 79c75cd

Browse files
authored
Refactored Simplify Path.java
1 parent a84ac18 commit 79c75cd

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

Medium/Simplify Path.java

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,22 @@
11
class Solution {
22
public String simplifyPath(String path) {
33
Stack<String> stack = new Stack<>();
4-
StringBuilder sb = new StringBuilder();
5-
int idx = 0;
6-
int n = path.length();
7-
while (idx < n) {
8-
if (path.charAt(idx) == '/') {
9-
idx++;
10-
while (idx < n && path.charAt(idx) != '/') {
11-
sb.append(path.charAt(idx++));
12-
}
13-
String dir = sb.toString();
14-
sb.setLength(0);
15-
if (dir.equals("..")) {
16-
if (!stack.isEmpty()) {
17-
stack.pop();
18-
}
19-
}
20-
else if (dir.equals(".") || dir.length() == 0) {
21-
continue;
22-
}
23-
else {
24-
stack.push(dir);
4+
String[] splits = path.split("/");
5+
for (String split : splits) {
6+
if (split.equals("") || split.equals(".")) {
7+
continue;
8+
} else if (split.equals("..")) {
9+
if (!stack.isEmpty()) {
10+
stack.pop();
2511
}
12+
} else {
13+
stack.push(split);
2614
}
2715
}
28-
sb = new StringBuilder();
16+
StringBuilder resultingPath = new StringBuilder();
2917
while (!stack.isEmpty()) {
30-
sb.insert(0, stack.pop());
31-
sb.insert(0, "/");
18+
resultingPath.insert(0, stack.pop()).insert(0, "/");
3219
}
33-
return sb.length() > 0 ? sb.toString() : "/";
20+
return resultingPath.length() == 0 ? "/" : resultingPath.toString();
3421
}
3522
}

0 commit comments

Comments
 (0)