leetcode 32. Longest Valid Parentheses

括号匹配当然是用栈了,这里用一个Int栈,因为既要存储数字,又要存储括号。注意这里的数字是临时的括号匹配数量,而'('=40,是个偶数,所以随便用一个奇数代替左括号。

算法就是从左向右扫描,遇到左括号就入栈,遇到右括号有三种情况:

1.栈顶是左括号,那么用2取代那个左括号,这时如果栈顶下边是个数字,就要加上这个二;

2.栈顶是数字,数字下边是个左括号,也就是"(数字)"的情况,用数字+2代替左括号,栈顶下降。再向前检查看是不是数字,是数字就合并。

3.栈顶是数字,数字下边是(。直接将)入栈。



int longestValidParentheses(char* s) {
    int maxRet,head,lenS,i;
    int *temp;
    lenS=strlen(s);
    temp=(int *)malloc(sizeof(int)*lenS);
    head=0;//栈顶
    maxRet=0;

    for(i=0;i<lenS;i++)
    {
        if(s[i]=='(')
        {
            temp[head++]=43;  //本来想存储左括号,但是(的ascll值是一个偶数,这个算法还想存储一些数字(都是偶数),因此用一个基数代替'('
        }
        else
        {
            if(head>0&&temp[head-1]==43)
            {
                temp[head-1]=2;
                if(head>1&&temp[head-2]!=43&&temp[head-2]!=')')//'数字''数字'的情况
                {
                    temp[head-2]=temp[head-2]+2;
                    head--;
                }

            }
            else if(head>1&&temp[head-1]!=43&&temp[head-1]!=')'&&temp[head-2]==43)   //"('数字')"的情况
            {
                temp[head-2]=temp[head-1]+2;
                head--;
                if(head>1&&temp[head-1]!=43&&temp[head-1]!=')'&&temp[head-2]!=43&&temp[head-2]!=')')
                {
                    temp[head-2]=temp[head-1]+temp[head-2];
                    head--;
                }
            }
            else
            {
                temp[head++]=')';
            }


        }
    }
    for(i=0;i<head;i++)
        if(temp[i]>maxRet&&temp[i]!=43&&temp[i]!=')')
            maxRet=temp[i];
    return maxRet;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值