目录
算法思路
-
初始化: 辅助栈 stack ,弹出序列的索引 i ;
-
遍历压栈序列:
各元素记为
num
- 元素
num
入栈; - 循环出栈:若
stack
的栈顶元素 = 弹出序列元素popped[i]
,则执行出栈与i++
;
- 元素
-
返回值: 若
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