题目

image.png

解题思路

image.png
image.png

实现

1、辅助栈模拟操作法

题目指出 pushed 是 popped 的排列 。因此,无需考虑 pushed 和 popped 长度不同 或 包含元素不同 的情况。

  1. class Solution {
  2. public boolean validateStackSequences(int[] pushed, int[] popped) {
  3. Stack<Integer> stack = new Stack<>();
  4. int i = 0;
  5. for (int num : pushed) {
  6. // num 入栈
  7. stack.push(num);
  8. // 循环判断与出栈
  9. while (!stack.isEmpty() && stack.peek() == popped[i]) {
  10. stack.pop();
  11. i++;
  12. }
  13. }
  14. return stack.isEmpty();
  15. }
  16. }

image.png