题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解法
我的解法:借助临时栈
新建一个栈,将数组A压入栈中,当栈顶元素等于数组B时,就将其出栈,当循环结束时,判断栈是否为空,若为空则返回true。
代码:
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV)
{
stack<int> s;
int index1=0,index2=0;
while(index1<pushV.size()&&index2<popV.size()){
if(pushV[index1]==popV[index2]){
index1++;
index2++;
while(s.empty()==0){
if(s.top()!=popV[index2])
break;
else{
index2++;
s.pop();
}
}
}
else{
s.push(pushV[index1]);
index1++;
}
}
if(index1!=index2)
return false;
else
return true;
}
};
但我写的太复杂了,感觉代码行数过多,看看优化后的版本。
代码:
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV)
{
stack<int> s;
int index1=0,index2=0;
while(index1<pushV.size()){
s.push(pushV[index1++]);
while(index2<popV.size()&&s.top()==popV[index2]){
s.pop();
index2++;
}
}
if(s.empty()==0)
return false;
return true;
}
};