946. 验证栈序列 中等

  1. class Solution {
  2. public boolean validateStackSequences(int[] pushed, int[] popped) {
  3. LinkedList<Integer> stack = new LinkedList<>();
  4. int n = pushed.length;
  5. int index = 0;
  6. for (int i=0; i<n; i++) {
  7. int cur = popped[i];
  8. for ( ; index<=n; index++) {
  9. if (!stack.isEmpty() && stack.getLast() == cur) {
  10. stack.pollLast();
  11. break;
  12. }
  13. if (index < n) {
  14. stack.addLast(pushed[index]);
  15. }
  16. }
  17. }
  18. return stack.isEmpty();
  19. }
  20. }