zoukankan      html  css  js  c++  java
  • 【数据结构】算法 Validate Stack Sequence 验证栈序列

    Validate Stack Sequence 验证栈序列

    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.

    给了2个序列的入栈,出栈,按照2个栈的顺序,判断是否能将这个栈元素完全处理完。

    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
    

    思路

    既然是栈,要出栈肯定是栈顶元素,或者就是下一个要入栈的元素。除了这2个情况,其他肯定不可能。

    按照popped数组,扫描pushed数组,一个个入栈

    public boolean validateStackSequences(int[] pushed, int[] popped) {
            Stack<Integer> s = new Stack<>();
            int j=0;
            for (int i = 0; i < popped.length; i++) {
                //focus on out stack,
                //if popped stack top not equal pushed e ,push e until find e equal poped top
                //then s.pop,
                while (j<pushed.length&&(!s.isEmpty()||s.peek()!=popped[i])){
                    s.push(pushed[j]);
                    j+=1;
                }
                if (s.peek()!=popped[i]){
                    return false;
                }
                s.pop();
            }
            return true;
        }
    

    Tag

    stack

  • 相关阅读:
    Codevs2822 爱在心中
    3098: Hash Killer II
    课程总结
    团队作业——个人总结
    团队作业2
    团队个人分工
    装甲车团队介绍(别急,在做了)
    面向对象程序设计作业(4)
    面向对象程序设计作业(3)
    面向对象程序设计(2)
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14587877.html
Copyright © 2011-2022 走看看