剑指offer31 栈的压入、弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。
假设压入栈的所有数字均不相等。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
注意:若两个序列长度不等则视为并不是一个栈的压入、弹出序列。若两个序列都为空,则视为是一个栈的压入、弹出序列。
样例
输入:[1,2,3,4,5]
[4,5,3,2,1]
输出:true
思路:
用一个栈去模拟,把进栈队列依次入站,然后碰到出栈队列则出栈,最后判断栈是否为空以及进栈队列是否都已进栈,出栈队列是否都出栈。
AcWing-42 c++ code:
class Solution {
public:
bool isPopOrder(vector<int> pushV,vector<int> popV) {
if(pushV.size() != popV.size()){
return false;
}
int n = pushV.size();
stack<int> nums;
int indexPop = 0;
for(int i = 0; i < n; i++){
nums.push(pushV[i]);
while(!nums.empty() && nums.top() == popV[indexPop]){
nums.pop();
indexPop++;
}
}
if(indexPop == n){
return true;
}else{
return false;
}
}
};
AcWing-42 python code:
class Solution(object):
def isPopOrder(self, pushV, popV):
"""
:type pushV: list[int]
:type popV: list[int]
:rtype: bool
"""
if len(pushV) != len(popV):
return False
elif len(pushV) == len(popV) ==0:
return True
s = []
pushV_id = 0;
popV_id = 0;
n = len(pushV)
while pushV_id < n:
s.append(pushV[pushV_id])
pushV_id += 1
while len(s) != 0 and popV_id < n and s[-1] == popV[popV_id]:
s.pop()
popV_id += 1
if popV_id < n:
return False
else:
return True
本文详细介绍了如何判断一个序列是否为特定栈的合法弹出序列,通过使用辅助栈进行模拟,验证给定序列是否符合栈的压入和弹出规则。提供了C++和Python两种语言的实现代码。
433

被折叠的 条评论
为什么被折叠?



