Skip to content

Commit 763bf66

Browse files
refactor 71
1 parent 8f0148c commit 763bf66

File tree

1 file changed

+16
-31
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+16
-31
lines changed

src/main/java/com/fishercoder/solutions/_71.java

Lines changed: 16 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,39 +6,24 @@
66
import java.util.LinkedList;
77
import java.util.Set;
88

9-
/**
10-
* 71. Simplify Path
11-
12-
Given an absolute path for a file (Unix-style), simplify it.
13-
14-
For example,
15-
path = "/home/", => "/home"
16-
path = "/a/./b/../../c/", => "/c"
17-
18-
Corner Cases:
19-
Did you consider the case where path = "/../"?
20-
In this case, you should return "/".
21-
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
22-
In this case, you should ignore redundant slashes and return "/home/foo".
23-
*/
249
public class _71 {
2510

26-
public static class Solution1 {
27-
public String simplifyPath(String path) {
28-
Deque<String> stack = new LinkedList<>();
29-
Set<String> skipSet = new HashSet<>(Arrays.asList("..", ".", ""));
30-
for (String dir : path.split("/")) {
31-
if (dir.equals("..") && !stack.isEmpty()) {
32-
stack.pop();
33-
} else if (!skipSet.contains(dir)) {
34-
stack.push(dir);
11+
public static class Solution1 {
12+
public String simplifyPath(String path) {
13+
Deque<String> stack = new LinkedList<>();
14+
Set<String> skipSet = new HashSet<>(Arrays.asList("..", ".", ""));
15+
for (String dir : path.split("/")) {
16+
if (dir.equals("..") && !stack.isEmpty()) {
17+
stack.pop();
18+
} else if (!skipSet.contains(dir)) {
19+
stack.push(dir);
20+
}
21+
}
22+
String result = "";
23+
for (String dir : stack) {
24+
result = "/" + dir + result;
25+
}
26+
return result.isEmpty() ? "/" : result;
3527
}
36-
}
37-
String result = "";
38-
for (String dir : stack) {
39-
result = "/" + dir + result;
40-
}
41-
return result.isEmpty() ? "/" : result;
4228
}
43-
}
4429
}

0 commit comments

Comments
 (0)