| 1 | class Solution { |
| 2 | public boolean validateStackSequences(int[] pushed, int[] popped) { |
| 3 | Stack<Integer> inStack = new Stack<>(); |
| 4 | int posPush = 0, posPop = 0; |
| 5 | while (posPush != pushed.length) { |
| 6 | int curr = pushed[posPush]; |
| 7 | while (!inStack.empty() && popped.length > 0 && inStack.peek() == popped[posPop]) { |
| 8 | inStack.pop(); |
| 9 | posPop++; |
| 10 | } |
| 11 | if (popped.length == 0) break; |
| 12 | if (curr == popped[posPop]) posPop++; |
| 13 | else inStack.push(curr); |
| 14 | posPush++; |
| 15 | } |
| 16 | while (!inStack.empty() && popped.length > 0 && inStack.peek() == popped[posPop]) { |
| 17 | inStack.pop(); |
| 18 | posPop++; |
| 19 | } |
| 20 | if (inStack.empty()) return true; |
| 21 | return false; |
| 22 | } |
| 23 | } |