[LeetCode] 946. Validate Stack Sequences 验证栈序列


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.

这道题给了两个序列 pushed 和 popped,让判断这两个序列是否能表示同一个栈的压入和弹出操作,由于栈是后入先出的顺序,所以并不是任意的两个序列都是满足要求的。比如例子2中,先将 1,2,3,4 按顺序压入栈,此时4和3出栈,接下来压入5,再让5出栈,接下来出栈的是2而不是1,所以例子2会返回 false。而这道题主要就是模拟这个过程,使用一个栈,和一个变量i用来记录弹出序列的当前位置,此时遍历压入序列,对遍历到的数字都压入栈,此时要看弹出序列当前的数字是否和栈顶元素相同,相同的话就需要移除栈顶元素,并且i自增1,若下一个栈顶元素还跟新位置上的数字相同,还要进行相同的操作,所以用一个 while 循环来处理。直到最终遍历完压入序列后,若此时栈为空,则说明是符合题意的,否则就是 false,参见代码如下:


class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> st;
        int i = 0;
        for (int num : pushed) {
        	st.push(num);
        	while (!st.empty() && st.top() == popped[i]) {
        		st.pop();
        		++i;
        	}
        }
        return st.empty();
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/946


参考资料:

https://leetcode.com/problems/validate-stack-sequences/

https://leetcode.com/problems/validate-stack-sequences/discuss/197685/C%2B%2BJavaPython-Simulation-O(1)-Space


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2020-05-26 03:44  Grandyang  阅读(2085)  评论(0编辑  收藏  举报
Fork me on GitHub