Skip to content

Commit dc7e06f

Browse files
add one more solution for 946
1 parent 393cee9 commit dc7e06f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

+28
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,32 @@ public boolean validateStackSequences(int[] pushed, int[] popped) {
2727
return stack.isEmpty();
2828
}
2929
}
30+
31+
public static class Solution2 {
32+
public boolean validateStackSequences(int[] pushed, int[] popped) {
33+
Stack<Integer> stack = new Stack<>();
34+
int i = 0;
35+
int j = 0;
36+
int len = pushed.length;
37+
while (i < len) {
38+
if (pushed[i] == popped[j]) {
39+
i++;
40+
j++;
41+
} else if (!stack.isEmpty() && stack.peek() == popped[j]) {
42+
stack.pop();
43+
j++;
44+
} else {
45+
stack.push(pushed[i++]);
46+
}
47+
}
48+
while (j < len) {
49+
if (!stack.isEmpty() && stack.peek() != popped[j++]) {
50+
return false;
51+
} else {
52+
stack.pop();
53+
}
54+
}
55+
return true;
56+
}
57+
}
3058
}

src/test/java/com/fishercoder/_946Test.java

+6
Original file line numberDiff line numberDiff line change
@@ -9,29 +9,35 @@
99
public class _946Test {
1010

1111
private static _946.Solution1 solution1;
12+
private static _946.Solution2 solution2;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _946.Solution1();
17+
solution2 = new _946.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
assertEquals(true, solution1.validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 5, 3, 2, 1}));
23+
assertEquals(true, solution2.validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 5, 3, 2, 1}));
2124
}
2225

2326
@Test
2427
public void test2() {
2528
assertEquals(false, solution1.validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 3, 5, 1, 2}));
29+
assertEquals(false, solution2.validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 3, 5, 1, 2}));
2630
}
2731

2832
@Test
2933
public void test3() {
3034
assertEquals(true, solution1.validateStackSequences(new int[]{}, new int[]{}));
35+
assertEquals(true, solution2.validateStackSequences(new int[]{}, new int[]{}));
3136
}
3237

3338
@Test
3439
public void test4() {
3540
assertEquals(false, solution1.validateStackSequences(new int[]{4, 0, 1, 2, 3}, new int[]{4, 2, 3, 0, 1}));
41+
assertEquals(false, solution2.validateStackSequences(new int[]{4, 0, 1, 2, 3}, new int[]{4, 2, 3, 0, 1}));
3642
}
3743
}

0 commit comments

Comments
 (0)