AdamDuncan

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

压入序列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;
}

posted on 2017-09-16 13:21  AdamDuncan  阅读(369)  评论(0编辑  收藏  举报