【leetcode】Longest Valid Parentheses

问题:

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

分析:

【1】若s[i]=='(' ,则压栈 stack.push(i);

【2】若s[i]=')' ,如果这个时候栈是空的,那么记录最后一个')'的位置:  last=i ;

【3】如果s[i]=')' ,如果这个时候栈是非空的,弹栈:

         (3.1)出栈后,如果栈为空,那么当前序列的最长合法括号的长度为i-last  (匹配已经完成);

         (3.2)出栈后,如果栈为非空,那么当前序列的最长合法括号的长度为i-buffer.top(). (匹配可能还没有完成);

代码:

class Solution{
public:
    int longestValidParentheses(string s) {
        int max_len=0;
        //字符串中出现')',但存(的栈为空,那么last就存这个)的坐标
        int last=-1;
        //放'('的栈 stk
        stack<int> stk;
        for(int i=0;i<s.length();i++){
            //只要遇到(就存栈stk
            if(s[i]=='('){
                stk.push(i);
            //遇到)
            }else{
                //存(的栈空,有效的括号长度从last以后算起
                if(stk.empty()){
                    last=i;
                //(栈不空
                }else{
                    stk.pop();
                    //刚好匹配,则长度为i-last;
                    //如果有多个()()(),i增而last不变,则长度是增加的
                    if(stk.empty()){
                        max_len=max(max_len,i-last);
                    }else{
                    //不匹配:((((),最大长度为i-stk.top()
                        max_len=max(max_len,i-stk.top());
                    }
                }
            }
        }
        return max_len;
    }
};  


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值