image.png

解决思路

贪心

image.png

  1. public boolean validStackSequences(int[] pushed,int[] poped){
  2. int N = pushed.length;
  3. Stack<Integer> stack = new Stack<>();
  4. int j = 0;
  5. for(int x:pushed){
  6. stack.push(x);
  7. //判断是否栈顶的元素为弹出的序列
  8. while (!stack.isEmpty() && j < N && stack.peek()==poped[j]){
  9. stack.pop();
  10. j++;
  11. }
  12. }
  13. return j == N;
  14. }