题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列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