-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSolution.java
33 lines (30 loc) · 892 Bytes
/
Solution.java
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
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
if (pushed.length != popped.length) { return false; }
Stack<Integer> s = new Stack<>();
int pi = 0;
int pj = 0;
while (pi < pushed.length) {
// Populate
if (s.empty() || (pushed[pi] != popped[pj] && s.peek() != popped[pj])) {
s.push(pushed[pi]);
pi++;
}
// Extract
if (pi < pushed.length && pushed[pi] == popped[pj]) {
s.push(pushed[pi]);
pi++;
}
if (s.peek() == popped[pj]) {
s.pop();
pj++;
}
}
while (!s.empty()) {
if (s.peek() != popped[pj]) { return false; }
s.pop();
pj++;
}
return true;
}
}