32. Longest Valid Parentheses

题目:Longest Valid Parentheses

原题链接:https://leetcode.com/problems/longest-valid-parentheses/?tab=Description

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.

给出一个字符串只含有小括号符号“(”以及“)”,找出字符串中合法的(即符合括号匹配规则)子串中的最长值。
例:
对与”(()”,最长的合法子串是 “()”,所以长度是2。
对于”)()())”,最长的合法子串是”()()”,所以长度是4。

思路

使用暴力查找的话会超时,效率很低。
我们可以先把字符串中已经配对好的那些子串给去掉,剩下的就只需要判断没有配对的括号之间的子串的长度就可以了。

代码

class Solution {
public:
    int longestValidParentheses(string s) {
        int len = s.length();
        if(len < 2) return 0;
        // st用来存放没有配对成功的字符的下标
        stack<int> st;
        // 扫描字符串,将没有办法配对成功的字符下标压入栈
        for(int i = 0; i < len; ++i) {
            if(s[i] == '(') st.push(i);
            else{
                if(!st.empty()){
                    if(s[st.top()] == '('){
                        st.pop();
                    }else{
                        st.push(i);
                    }
                }else{
                     st.push(i);
                }
            }
        }
        int res = 0;
        if(st.empty()){
            res = len; // 栈空则整个字符串都是配对好的
        }else{
            // 每次选取栈顶元素,当前栈顶元素和前一个栈顶元素之间的区间则是配对符合要求的子串
            int a = len, b = 0; // a用来表示区间的左,b用来表示区间的右,注意初始的时候假设右
                                // 是len
            while(!st.empty()){
                b = a;
                a = st.top();
                st.pop();
                res = max(res, b - a - 1);
            }
            // 考虑栈底元素之前的子串
            res = max(res, a);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值