Skip to content

Commit 53703d4

Browse files
authored
Refactored Validate Stack Sequences.java
1 parent 00ab1ba commit 53703d4

File tree

1 file changed

+11
-17
lines changed

1 file changed

+11
-17
lines changed

Medium/Validate Stack Sequences.java

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,22 @@
11
class Solution {
22
public boolean validateStackSequences(int[] pushed, int[] popped) {
3-
int pushStart = 0;
4-
int popStart = 0;
53
Stack<Integer> stack = new Stack<>();
6-
while (pushStart < pushed.length && popStart < popped.length) {
7-
if (stack.isEmpty()) {
8-
stack.push(pushed[pushStart++]);
9-
}
10-
else {
11-
if (stack.peek() == popped[popStart]) {
12-
stack.pop();
13-
popStart++;
14-
}
15-
else {
16-
stack.push(pushed[pushStart++]);
17-
}
4+
int pushedIdx = 0;
5+
int poppedIdx = 0;
6+
while (pushedIdx < pushed.length && poppedIdx < popped.length) {
7+
if (!stack.isEmpty() && stack.peek() == popped[poppedIdx]) {
8+
stack.pop();
9+
poppedIdx++;
10+
} else {
11+
stack.push(pushed[pushedIdx++]);
1812
}
1913
}
20-
while (popStart < popped.length) {
21-
if (stack.peek() != popped[popStart]) {
14+
while (poppedIdx < popped.length) {
15+
if (stack.peek() != popped[poppedIdx]) {
2216
return false;
2317
}
18+
poppedIdx++;
2419
stack.pop();
25-
popStart++;
2620
}
2721
return true;
2822
}

0 commit comments

Comments
 (0)