zoukankan      html  css  js  c++  java
  • 0946. Validate Stack Sequences (M)

    Validate Stack Sequences (M)

    题目

    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.
    

    Constraints:

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

    题意

    给定一个栈的入栈顺序表和出栈顺序表,判断能否实现对应的出入栈操作(符合先进后出)。

    思路

    贪心+模拟。维护一个栈,当栈顶元素和出栈表的下一个元素相同时,立即出栈;否则压入入栈表的下一个元素。反证法证明正确性:栈中元素都不相同,记当前出栈表的第一个元素为x,如果栈顶元素也为x,且选择不出栈,那么x必然不会成为第一个出栈的元素,矛盾。


    代码实现

    Java

    class Solution {
        public boolean validateStackSequences(int[] pushed, int[] popped) {
            Deque<Integer> stack = new ArrayDeque<>();
            int i = 0, j = 0;
            
            while (j < popped.length) {
                if (i == pushed.length && stack.peek() != popped[j]) return false;
    
                if (stack.isEmpty() || stack.peek() != popped[j]) {
                    stack.push(pushed[i++]);
                } else {
                    stack.pop();
                    j++;
                }
            }
            
            return true;
        }
    }
    
  • 相关阅读:
    B站14天数据分析笔记6次课笔记
    B站14天数据分析笔记5次课作业
    B站14天数据分析笔记5次课Pandas
    1037 在霍格沃茨找零钱 (20 point(s))
    第一章:第三节探索性数据分析
    Java没有运行选项
    Eclipse截图的时候错误提示消失/复制粘贴错误信息
    错误记录_css属性的值一定不需要引号么?
    错误记录_语法哪里错了?
    微软输入法使用
  • 原文地址:https://www.cnblogs.com/mapoos/p/14454269.html
Copyright © 2011-2022 走看看