xinyu04

导航

[Oracle] LeetCode 32 Longest Valid Parentheses 思维

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

Solution

不妨把左括号记为 \(+1\), 右括号记为 \(-1\),那么合理的组合满足前缀和 \(\ge 0\), 且总和为 \(0\). 但是要注意到也可以从右端开始

点击查看代码
class Solution {
private:
    int sol(string s){
        int cnt=0;
        int res=0;
        int st=0;
        for(int i=0;i<s.size();i++){
            if(s[i]=='(')cnt++;
            else{
                cnt--;
                if(!cnt){
                    res=max(res, i-st+1);
                }
                else if(cnt<0) st=i+1,cnt=0;
            }
        }
        return res;
    }
public:
    int longestValidParentheses(string s) {
        int cand1 = sol(s);
        reverse(s.begin(),s.end());
        for(auto& ele:s)ele^=1;
        return max(cand1, sol(s));
    }
};

posted on 2022-09-26 16:21  Blackzxy  阅读(12)  评论(0编辑  收藏  举报