1. 程式人生 > >劍指offer66題--Java實現,c++實現和python實現 21.棧的壓入、彈出序列

劍指offer66題--Java實現,c++實現和python實現 21.棧的壓入、彈出序列

題目描述

輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)

C++

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        stack<int> st;
        for(int i=0,j=0;i<pushV.size();i++)
        {
            for(st.push(pushV[i]);j<popV.size()&&st.top()==popV[j]&&!st.empty();st.pop(),j++);//只有在相等的時候才彈出           
        }
        return st.empty();  
    }
};

Java

import java.util.ArrayList;
import java.util.Stack;
import java.util.Objects;
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      if (null == pushA || null == popA) {
          return false;
      }
        Stack<Integer> stack1 = new Stack<Integer>();
        int pushLength = pushA.length;
        int popLength = popA.length;
        int i = 0;
        int j = 0;
        while(i<pushLength && j<popLength) {
            stack1.push(pushA[i]);//先壓入一個元素到棧
            while (!stack1.empty() && Objects.equals(popA[j], stack1.peek())) {
                stack1.pop();//相等則彈出
                j++;//彈出序列後移
            }
            i++;//壓棧序列繼續向後移
        }
        return stack1.empty();
    }
}

python

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if not pushV or len(pushV)!=len(popV):
            return 0
        stack = []
        for v in pushV:
            stack.append(v)
            while len(stack) and stack[-1]==popV[0]:
                stack.pop()
                popV.pop(0)
        if len(stack):
            return 0
        return 1