题目描述:
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.
这道题为hard难度,但是用动态规划就很简单,而且算法效率也很高。
先定义dp数组,定义dp[i]表示以s[i]结尾的最大有效括号匹配的长度。那么对于s[i+1],如果其为左括号,则很明显它不可能作为有效括号匹配的结尾,所以dp[i+1]=0;而当s[i+1]为右括号时,可以进行递推:即设j=i-dp[i],那么s[j]为以s[i]为结尾的最长括号匹配字符串的前一位字符,如果s[j]为右括号,那么它无法和s[i+1]匹配,此时dp[i+1]=0;但是当s[i+1]为左括号时,显然dp[i+1]=2+dp[i],即以s[i]为结尾的最长括号匹配,再加上s[j]和s[i+1],但是还要注意在s[j]之前可能还存在有效的括号匹配,可以直接加入之前得到的括号匹配字符串中,所以dp[i+1]还要加上dp[j-1]。
class Solution {
public:
int longestValidParentheses(string s) {
if(s.empty()) return 0;
stack<int> par;
int max_length=0;
int dp[s.size()]={};
for(int i=0;i<(s.size()-1);i++)
{
if(s[i+1]=='(') dp[i+1]=0;
int j=i-dp[i];
if(s[i+1]==')'&&j>=0)
{
if(s[j]==')') dp[i+1]=0;
if(s[j]=='(')
{
dp[i+1]=2+dp[i];
if((j-1)>=0)
dp[i+1]+=dp[j-1];
}
}
max_length=max(max_length,dp[i+1]);
}
return max_length;
}
};