/**
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
因为可以有如下的push和pop序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的pop序列就是4、5、3、2、1。
但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。
**/
#include <exception>
#include <string>
#include <stack>
#include <iostream>
bool conform(const std::string& seq,std::string& pop)
{
std::stack<char> st;
auto s_index=seq.begin();
auto p_index=pop.begin();
while(s_index!=seq.end() || !st.empty())
{
if(s_index==seq.end())
if(st.top()!=*p_index)
break;
else
{
st.pop();
++p_index;
continue;
}
if(*s_index==*p_index)
{
//std::cout<<"push:"<<*s_index<<std::endl;
//std::cout<<"pop:"<<*s_index<<std::endl;
++s_index;
++p_index;
}
else if(!st.empty() && st.top()==*p_index)
{
//std::cout<<"pop:"<<st.top()<<std::endl;
st.pop();
++p_index;
}
else
{
//std::cout<<"push:"<<*s_index<<std::endl;
st.push(*s_index);
++s_index;
}
}
if(s_index==seq.end() && p_index==pop.end() && st.empty())
return true;
return false;
}
int main(int argc,char* argv[])
{
std::string seq("12345");
std::string pop("43512");
std::cout<<conform(seq,pop)<<std::endl;
system("PAUSE");
return 0;
}
判断一个序列是不是另外一个序列的栈的pop序列
最新推荐文章于 2020-03-28 21:09:57 发布