Skip to content

Commit ffeee6a

Browse files
add a solution for 71
1 parent 27bb9da commit ffeee6a

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_71.java

+27
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
public class _71 {
1010

1111
public static class Solution1 {
12+
/**
13+
* For LinkedList class in Java, if you use pop(), then you'll have to use push() as its corresponding method to remove from the "top" of the stack, using pollLast() will not work.
14+
*/
1215
public String simplifyPath(String path) {
1316
Deque<String> stack = new LinkedList<>();
1417
Set<String> skipSet = new HashSet<>(Arrays.asList("..", ".", ""));
@@ -26,4 +29,28 @@ public String simplifyPath(String path) {
2629
return result.isEmpty() ? "/" : result;
2730
}
2831
}
32+
33+
public static class Solution2 {
34+
/**
35+
* This solution doesn't vary too much from the above one, except in that it's using pollLast() and addLast() instead of pop() and push().
36+
*/
37+
public String simplifyPath(String path) {
38+
Set<String> skip = new HashSet(Arrays.asList("..", ".", ""));
39+
Deque<String> stack = new LinkedList();
40+
String[] directories = path.split("/");
41+
for (String dir : directories) {
42+
if (dir.equals("..") && !stack.isEmpty()) {
43+
stack.pollLast();
44+
} else if (!skip.contains(dir)) {
45+
stack.addLast(dir);
46+
}
47+
}
48+
StringBuilder sb = new StringBuilder();
49+
while (!stack.isEmpty()) {
50+
sb.append("/");
51+
sb.append(stack.pollFirst());
52+
}
53+
return sb.length() == 0 ? "/" : sb.toString();
54+
}
55+
}
2956
}

Diff for: src/test/java/com/fishercoder/_71Test.java

+14
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@
88

99
public class _71Test {
1010
private static _71.Solution1 solution1;
11+
private static _71.Solution2 solution2;
1112

1213
@BeforeEach
1314
public void setup() {
1415
solution1 = new _71.Solution1();
16+
solution2 = new _71.Solution2();
1517
}
1618

1719
@Test
@@ -33,4 +35,16 @@ public void test3() {
3335
public void test4() {
3436
assertEquals("/", solution1.simplifyPath("/."));
3537
}
38+
39+
@Test
40+
public void test5() {
41+
// assertEquals("/home/user/Pictures", solution1.simplifyPath("/home/user/Documents/../Pictures"));
42+
assertEquals("/home/user/Pictures", solution2.simplifyPath("/home/user/Documents/../Pictures"));
43+
}
44+
45+
@Test
46+
public void test6() {
47+
assertEquals("/", solution1.simplifyPath("/../"));
48+
assertEquals("/", solution2.simplifyPath("/../"));
49+
}
3650
}

0 commit comments

Comments
 (0)