zoukankan      html  css  js  c++  java
  • 剑指offer | 栈的压入,弹出序列 | 10

    算法思路

    1. 初始化: 辅助栈 stack ,弹出序列的索引 i ;

    2. 遍历压栈序列:

      各元素记为num

      1. 元素 num入栈;
      2. 循环出栈:若 stack 的栈顶元素 = 弹出序列元素 popped[i] ,则执行出栈与 i++
    3. 返回值:stack 为空,则此弹出序列合法。

    cpp

    class Solution {
    public:
        bool IsPopOrder(vector<int> pushV,vector<int> popV) {
            if(pushV.size() != popV.size())return false;
            stack<int> Shelp;
            int i=0;
            for(auto x:pushV){
                Shelp.push(x);
                while(Shelp.size() && Shelp.top()==popV[i]){
                    Shelp.pop();
                    i++;
                }
            }
            return Shelp.empty();
        }
    };
    

    python

    # -*- coding:utf-8 -*-
    class Solution:
        def IsPopOrder(self, pushV, popV):
            if len(pushV)!=len(popV):return False
            Shelp = []
            i = 0
            for x in pushV:
                Shelp.append(x)
                while Shelp and Shelp[-1]==popV[i]:
                    Shelp.pop()
                    i+=1
            return not Shelp
    
  • 相关阅读:
    node
    ionic
    关于websocket和ajax无刷新
    HTML图片热区
    npm -D -S -g -i 以及安装技巧
    es6 webpack转es5
    es6
    es6
    ssh tunnel
    vim上次和下次光标位置
  • 原文地址:https://www.cnblogs.com/Rowry/p/14305341.html
Copyright © 2011-2022 走看看