剑指offer第21题(栈的压入、弹出序列)

来源:互联网 发布:学大数据看什么书 编辑:程序博客网 时间:2024/05/16 10:04

题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思想:判断一个序列是不是栈的弹出序列的规律:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果不是,我们就需要继续入栈,如果所有的数字都压入栈还没有找到合适的数字,则不是弹出序列。

java代码:

import java.util.ArrayList;import java.util.Stack;public class Solution {    public boolean IsPopOrder(int [] pushA,int [] popA) {        if(pushA.length==0||popA.length==0){            return false;        }        Stack<Integer> stack=new Stack<Integer>();        int j=0;        for(int i=0;i<popA.length;i++){            stack.push(pushA[i]);            while(j<popA.length&&stack.peek()==popA[j]){                stack.pop();                j++;            }        }        return stack.isEmpty();    }}

python代码:

# -*- coding:utf-8 -*-class Solution:    def IsPopOrder(self, pushV, popV):        if popV==None or pushV==None:            return False        tempsatck=[]        for i in pushV:            tempsatck.append(i)            while len(tempsatck) and tempsatck[-1]==popV[0]:                tempsatck.pop()                popV.pop(0)        if len(tempsatck):            return False        return True

阅读全文
0 0
原创粉丝点击