Leetcode 剑指 Offer 31 弹出序列

39 篇文章 0 订阅
34 篇文章 0 订阅

这道题主要考察对各种可能出现情况的分析判断。
具体分析参考剑指offer31.

P.S. 前几次提交的时候超出了规定时间,在编写代码时需要注意代码的规范。

时间和内存消耗以及源代码如下:
时间和内存消耗

bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize){
    if  (pushed ==  NULL    &&  popped  ==  NULL)
    {
        return  true;
    }

    if  (poppedSize !=  pushedSize)
    {
        return  false;
    }

    int* temp   =   (int*) malloc (pushedSize*sizeof(int));
    int  countTemp      =   0;
    int  countPushed    =   0;
    int  countPopped    =   0;
    
    while   (countPushed < pushedSize   &&  countPopped < poppedSize)
    {
        if  (pushed[countPushed] == popped[countPopped])
        {
            while  (pushed[countPushed] == popped[countPopped])
            {
                countPushed++;
                countPopped++;
                if  (countPopped == poppedSize
                ||  countPushed  == pushedSize)
                {
                    break;
                }
            }
        }        


        else    if  (countTemp > 0)
        {
            countTemp--;
            while  (temp[countTemp] ==   popped[countPopped])
            {
                temp[countTemp] =   NULL;
                countTemp--;
                countPopped++;

                if  (countTemp < 0)
                {
                    break;
                }
            }
            countTemp++;
            temp[countTemp] =   pushed[countPushed];
            countTemp++;
            countPushed++;
        }

        else
        {
            temp[countTemp] =   pushed[countPushed];
            countTemp++;
            countPushed++;
        }

    }

    if  (countTemp  ==  0)
    {
        return  true;
    }

    countTemp--;

    while   (countTemp >= 0 &&  countPopped < poppedSize)
    {
        if  (temp[countTemp] != popped[countPopped])
        {
            return  false;
        }
        else    if  (countTemp == 0 &&  countPopped ==  (poppedSize-1))
        {
            return  true;
        }
        else
        {
            countTemp--;
            countPopped++;
        }
    }


    return  false;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值