32. Longest Valid Parentheses
Hard
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
Accepted
224,948
Submissions
845,931
这里参考了https://blog.youkuaiyun.com/weixin_38823568/article/details/80997966
class Solution {
public:
int longestValidParentheses(string s) {
if(s=="") return 0;
int len=s.length();
int _max=0;
int dp[len]={};//dp[i]表示以s[i]为首位字符到结尾字符的字符串的最长匹配长度
for(int i=len-2;i>=0;i--){
int temp=i+1+dp[i+1];//temp代表要找的匹配字符的位置
if(s[i]=='('&&temp<len&&s[temp]==')'){//判断是否匹配
dp[i]=dp[i+1]+2;
if(temp+1<len){//匹配的基础上如果下一个匹配字串也相邻的话
dp[i]+=dp[temp+1];
}
}
_max=max(_max,dp[i]);
}
return _max;
}
};