zoukankan      html  css  js  c++  java
  • [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 题目讲解汇总(持续更新中...)

  • 相关阅读:
    小球下落
    生成1~n的排列
    hdu1871无题
    android本地定时通知
    php 5.3起弃用session_register
    centos 6.3 编译安装 nginx +mysql + php
    skynet网络库socketserver
    mac下通过docker搭建LEMP环境
    Git操作
    iOS本地通知
  • 原文地址:https://www.cnblogs.com/grandyang/p/12962469.html
Copyright © 2011-2022 走看看