[Leetcode] 32. Longest Valid Parentheses

来源:互联网 发布:saas平台多租户 mysql 编辑:程序博客网 时间:2024/06/07 22:30

题目

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.

找最长括号匹配

思路DP

dp[i]表示包含s[i]的最长匹配长度,若s[i] = ‘(‘,dp[i] = 0;s[i] = ‘)’才更新

如果s[i-1-dp[i-1]]==’(‘,则说明当前位置可以和i-1-dp[i-1]位置匹配,dp[i]=dp[i-1]+2;
然后还要加上匹配位置之前的最长长度dp[i]+=dp[i-dp[i]];
这里写图片描述

当i=8,因为dp[7] = 4, s[8 - 4 - 1] = s[3] = ‘(‘, 说明可以匹配,dp[8]=dp[7]+2=6。
还要加上dp[8-dp[8]]=dp[2]=2的长度,dp[8] += 2

    int longestValidParentheses(string s) {        s = ')' + s;        vector<int> dp(s.size(), 0);        int dp_size = s.size();        int res_max = 0;        for (int i = 1; i < dp_size; i++){            if (s[i] == ')'){                if (s[i - dp[i-1] - 1] == '(')                    dp[i] = dp[i-1] + 2;                dp[i] += dp[i - dp[i]];            }            res_max = std::max(dp[i], res_max);        }        return res_max;    }