码迷,mamicode.com
首页 > 编程语言 > 详细

判断出栈序列是否可能是某个入栈序列的出栈序列,C++

时间:2017-09-16 14:56:47      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:ems   val   isp   current   查看   map   c++   vector   判断   

主要思想栈必须满足先进后出的规则,例如:

压入序列1,2,3,4,5

出栈序列4,3,5,1,2

设定一个Max值代表目前已经出栈的压入序列索引号最大的值

如当4出栈的时候,目前Max是4,当3出栈的时候,就查看3,4是否出栈,如果出栈就正确

当1出栈的时候,目前Max是5,就查看1~5时候出栈,这时候2还没有出栈就认为这个出栈序列不符合先进后出

#include<iostream>
#include<map>
#include<vector>
#include<memory.h>
using namespace std;
class Solution {
map<int,int> inMap;
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
int max = 0;
//出栈序列和入栈序列个数不相等
if (popV.size() != pushV.size())
{
return false;
}
if (popV.size() == 0)
{
return true;
}
//当出栈序列和入栈序列个数一样大的时候,两个栈的元素相等就是对的
if (popV.size() == 1)
{
if (popV[0] != pushV[0])
{
return false;
} else {
return true;
}
}
if (popV.size() == 2)
{
if ((popV[0] ==pushV[0] && popV[1] == pushV[1]) ||( popV[0] == pushV[1] && pushV[0] == popV[1]))
{
return true;
} else {
return false;
}
}
for (int i = 0;i < pushV.size();i++)
{
inMap.insert(map<int,int>::value_type(pushV[i],i));
}
bool array[pushV.size()];
memset(array, false, sizeof(array));
int one = inMap.find(popV[0])->second;
int two = inMap.find(popV[1])->second;
array[one] = true;
array[two] = true;
if (one > two)
{
max = one;
} else {
max = two;
}
for (int i = 2;i< popV.size();i++)
{
map<int,int>::iterator currentIndex = inMap.find(popV[i]);
//currentIndex->first是key
if (currentIndex->second > max)
{
max = currentIndex->second;
}
array[currentIndex->second] = true;
for (int j = currentIndex->second; j <= max; j++)
{
if (array[j] == false)
{
return false;
}
}
}
return true;
}
};
int main()
{
int inArray[5] = {1,2,3,4,5};
int outArray[5] = {4,5,3,2,1};
//int outArray[5] = {4,3,5,1,2};
vector<int> pushV = vector<int>(&inArray[0], &inArray[5]);
vector<int> popV = vector<int>(&outArray[0], &outArray[5]);
for (int i = 0;i <pushV.size() ;i++)
{
cout<<pushV[i];
}

cout<<endl;
Solution solution = Solution();
cout<<solution.IsPopOrder(pushV, popV);
return 0;
}

判断出栈序列是否可能是某个入栈序列的出栈序列,C++

标签:ems   val   isp   current   查看   map   c++   vector   判断   

原文地址:http://www.cnblogs.com/adamhome/p/7531073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!