Just use a stack to simulate the push and pop process
While stack is empty or peek does not equal to popped current value, push value into stack.
While equal, pop stack and consume popped value.
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> s = new Stack<Integer>();
int i = 0, j = 0;
while (j < popped.length) {
if (s.size() == 0 || s.peek() != popped[j]) {
if (i == pushed.length) return false;
s.push(pushed[i++]);
}
else {
s.pop();
++j;
}
}
return true;
}
}