Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdc7e06f

Browse files
add one more solution for 946
1 parent393cee9 commitdc7e06f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,32 @@ public boolean validateStackSequences(int[] pushed, int[] popped) {
2727
returnstack.isEmpty();
2828
}
2929
}
30+
31+
publicstaticclassSolution2 {
32+
publicbooleanvalidateStackSequences(int[]pushed,int[]popped) {
33+
Stack<Integer>stack =newStack<>();
34+
inti =0;
35+
intj =0;
36+
intlen =pushed.length;
37+
while (i <len) {
38+
if (pushed[i] ==popped[j]) {
39+
i++;
40+
j++;
41+
}elseif (!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+
returnfalse;
51+
}else {
52+
stack.pop();
53+
}
54+
}
55+
returntrue;
56+
}
57+
}
3058
}

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,29 +9,35 @@
99
publicclass_946Test {
1010

1111
privatestatic_946.Solution1solution1;
12+
privatestatic_946.Solution2solution2;
1213

1314
@BeforeClass
1415
publicstaticvoidsetup() {
1516
solution1 =new_946.Solution1();
17+
solution2 =new_946.Solution2();
1618
}
1719

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

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

2832
@Test
2933
publicvoidtest3() {
3034
assertEquals(true,solution1.validateStackSequences(newint[]{},newint[]{}));
35+
assertEquals(true,solution2.validateStackSequences(newint[]{},newint[]{}));
3136
}
3237

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp