程序媛詹妮弗
终身学习

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

 

Note:

  1. 0 <= pushed.length == popped.length <= 1000
  2. 0 <= pushed[i], popped[i] < 1000
  3. pushed is a permutation of popped.
  4. pushed and popped have distinct values.

题意

给定两个序列push[]、popped[]。 用Stack验证用两个序列的元素,经过一番push和pop操作, Stack能为空

 

Solution: Stack

 

code

 1 class Solution {
 2     public boolean validateStackSequences(int[] pushed, int[] popped) {
 3         Stack<Integer> stack = new Stack<>();
 4         int i = 0;
 5         for (int p : pushed) {
 6             stack.push(p);
 7             while (!stack.isEmpty() && stack.peek() == popped[i]) {
 8                 stack.pop();
 9                 ++i;
10             }
11         }
12         return stack.empty();
13     }
14 }

 

posted on 2019-05-16 06:09  程序媛詹妮弗  阅读(320)  评论(0编辑  收藏  举报