Longest Valid Parentheses
Question Solution
Total Accepted: 47520 Total Submissions: 222865 Difficulty: Hard
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.
#include<iostream> #include<string> using namespace std; #define NUM 350 class Solution { public: int longestValidParentheses(string s) { int len = s.length(); if (len < 2) return 0; //int**dp= (int **)new int[10000][10000]; //int** isValid=(int **)new int[10000][10000]; //int max = 0; //memset(dp, 0, 10000 * 10000 * sizeof(int)); //memset(isValid, 0, 10000 * 10000 * sizeof(int)); int dp[NUM][NUM]; int isValid[NUM][NUM]; int max = 0; memset(dp, 0, NUM * NUM * sizeof(int));//会影响到结果输出 memset(isValid, 0, NUM * NUM * sizeof(int)); for (int i = 1; i < s.length(); ++i) { for (int j = i - 1; j >= 0; --j) { if (s[j] = ‘(‘&&s[i] == ‘)‘)//情况一 { int temp = 0; for (int k = j + 1; k < i; ++k) { if (isValid[j][k] && isValid[k + 1][i]) temp = 1; } if (i == j + 1 || dp[j + 1][i - 1] || temp) { isValid[j][i] = 1; dp[j][i] = i - j + 1; max = max > dp[j][i] ? max : dp[j][i]; } else { isValid[j][i] = 0; dp[j][i] = dp[j + 1][i] > dp[j][i - 1] ? dp[j + 1][i] : dp[j][i - 1]; } } else if (s[j] == ‘(‘&&s[i] == ‘(‘)//情况二 { isValid[j][i] = 0; dp[j][i] = dp[j][i - 1]; } else if (s[j] == ‘)‘&&s[i] == ‘)‘)//情况三 { isValid[j][i] = 0; dp[j][i] = dp[j + 1][i]; } else//情况四 { isValid[j][i] = 0; dp[j][i] = dp[j + 1][i - 1]; } } } return max; } }; int main() { Solution test; string s1 = ")(())()"; int res = test.longestValidParentheses(s1); cout << res << endl; return 0; }
无奈,只好搜索求助大神,dp:
这道题可以用一维动态规划逆向求解。假设输入括号表达式为String s,维护一个长度为s.length()的一维数组dp[],数组元素初始化为0。 dp[i]表示从s[i]到s[s.length - 1]最长的有效匹配括号子串长度。则存在如下关系:
dp[s.length - 1] = 0;从i - 2 到0逆向求dp[],并记录其最大值。
若s[i] == ‘(‘,则在s中从i开始到s.length - 1计算s[i]的值。这个计算分为两步,通过dp[i + 1]进行的(注意dp[i + 1]已经在上一步求解):
在s中寻找从i + 1开始的有效括号匹配子串长度,即dp[i + 1],跳过这段有效的括号子串,查看下一个字符,其下标为j = i + 1 + dp[i + 1]。若j没有越界,并且s[j] == ‘)’,则s[i ... j]为有效括号匹配,dp[i] =dp[i + 1] + 2。
在求得了s[i ... j]的有效匹配长度之后,若j + 1没有越界,则dp[i]的值还要加上从j + 1开始的最长有效匹配,即dp[j + 1]。
O(n)
1 int longestValidParentheses(string s) { 2 // Note: The Solution object is instantiated only once. 3 int slen = s.length(); 4 if(slen<2)return 0; 5 int max = 0; 6 int* dp = new int[slen]; 7 memset(dp,0,sizeof(int)*slen); 8 9 for(int i=slen-2; i>=0;i--) 10 { 11 if(s[i]==‘(‘) 12 { 13 int j = i+1+dp[i+1]; 14 if(j<slen && s[j]==‘)‘) 15 { 16 dp[i]=dp[i+1]+2; 17 int k = 0; 18 if(j+1<slen)k=dp[j+1]; 19 dp[i] += k; 20 } 21 max = max>dp[i]?max:dp[i]; 22 } 23 } 24 delete[] dp; 25 return max; 26 }
这段代码当真高明啊!!