-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution31.java
More file actions
35 lines (29 loc) · 865 Bytes
/
Solution31.java
File metadata and controls
35 lines (29 loc) · 865 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
if (pushed == null && popped == null) {
return true;
}
if (pushed == null || popped == null) {
return true;
}
if (pushed.length != popped.length) {
return false;
}
Stack<Integer> stack = new Stack<>();
int pushIndex = 0;
int popIndex = 0;
while (popIndex < popped.length) {
if (stack.isEmpty() || stack.peek() != popped[popIndex]) {
if (pushIndex < pushed.length) {
stack.push(pushed[pushIndex++]);
} else {
return false;
}
} else {
stack.pop();
popIndex++;
}
}
return true;
}
}