题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
if(pushV.size()!=popV.size())
return false;
stack <int> stack1;
int len=pushV.size();
int j=0;
int cnt=0;
for(int i=0; i<len; i++)
{
int n1=popV.at(i);
//第一阶段,匹配出栈的字符,匹配到的删除,同时将不匹配的入栈
if(j+cnt<len)
{
while(pushV.at(j)!=n1)
{
int n2=pushV.at(j);
stack1.push(n2);
j++;
if(j+cnt>=len)
return false;
}
pushV.erase(pushV.begin()+j);//在pushv中移除匹配的元素
cnt++;
}
//第二阶段,开始匹配栈中的元素,因为栈中元素已经固定,因此只要依次出栈对比即可,不一样则false。
else{
if(n1==stack1.top())
{
stack1.pop();
continue;
}
else
return false;
}
}
return true;
}
int main(){
bool i;
vector <int> push= {1,2,3,4,5};
vector <int> pop= {4,3,5,1,2};
i=IsPopOrder(push,pop);
cout<<i<<endl;
return 0;
}
非最优解,正常AC通过