LeetCode: Longest Valid Parentheses [031]

151 篇文章 0 订阅

【题目】


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.


【题意】

给定一个字符串,判定其中最长的有效括号子串的长度。


【思路】

所谓有效括号串可参见“vaid parentheses
本题的思路大体相同,仍然是维护一个栈,但入栈的元素不在是"("或")",而是字符串中相应的索引位。
当我们扫描完一遍字符串时,有效的连续括号子串会被从栈中清除,栈中留下的是剩余字符的索引位。
我们只需要计算剩余字符之间最大的索引间隔是多少即可。


【代码】

class Solution {
public:
    bool isPair(char left, char right){
        return left=='('&&right==')';
    }
    int longestValidParentheses(string s) {
        int len=s.length();
        if(len==0)return len;
        int result=0;       //初始化result
        stack<int> st;      //辅助栈,存放相应字符的索引位
        for(int i=0; i<len; i++){
            if(st.empty())st.push(i);
            else{
                if(isPair(s[st.top()],s[i]))st.pop();
                else st.push(i);
            }
        }
        //求最大子串长度
        int prev=len;
        while(!st.empty()){
            if(prev-st.top()-1>result)result=prev-st.top()-1;
            prev=st.top();
            st.pop();
        }
        if(prev>result)result=prev; //别忘了开头的那个子串
        return result;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值