zoukankan      html  css  js  c++  java
  • 判断出栈序列是否可能是某个入栈序列的出栈序列,C++

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

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

  • 相关阅读:
    关于css兼容性问题及一些常见问题汇总
    CSS3使用transition属性实现过渡效果
    CSS3 画基本图形,圆形、椭圆形、三角形等
    总结30个CSS3选择器
    javascript中call()、apply()的区别
    JavaScript面试技巧之数组的一些不low操作
    详解bootstrap-fileinput文件上传控件的亲身实践
    js控制随机数生成概率代码实例
    jQuery 第十章 工具方法-高级方法 $.ajax() $.Callbacks() .....
    jQuery 第九章 工具方法之插件扩展 $.extend() 和 $.fn.extend()
  • 原文地址:https://www.cnblogs.com/adamhome/p/7531073.html
Copyright © 2011-2022 走看看