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.
第一种解法是dynamic programming的解法,dp的解法可以从后面往前面推,或者从前面往后面推, 这一题我借鉴了ziyi_Google的写法:
https://leetcodenotes.wordpress.com/2013/10/19/leetcode-longest-valid-parentheses-%E8%BF%99%E7%A7%8D%E6%8B%AC%E5%8F%B7%E7%BB%84%E5%90%88%EF%BC%8C%E6%9C%80%E9%95%BF%E7%9A%84valid%E6%8B%AC%E5%8F%B7%E7%BB%84%E5%90%88%E6%9C%89%E5%A4%9A/
先定义dp中的数组opt, opt[i]就是代表从字符串i开始的位置,往后面数,longest valid parentheses. 这样的话就会有这样的情况
s[i] = ‘)’ 那么 dp[i] = 0, 因为从第i个位置开始的时候。如果字符是右括号 ‘)’. 那么从第i个位置开始的时候,肯定不能组成一个valid的parentheses.
所以dp数组推导公式就是
if(s[i]==’)’) dp[i] = 0;
if(s[i]==’(‘) dp[i] = dp[i+1]+2;
int j = (i + 1) + d[i + 1];
if (j < s.length() && s.charAt(j) == ‘)’) {
d[i] = d[i + 1] + 2; //(()())的外包情况
if (j + 1 < s.length())
d[i] += d[j + 1];//()()的后面还有的情况
//这种情况dp[i] = dp[i] + dp[j+1]; 适合 (()()()) ()()
代码如下:
public int longestValidParentheses(String s) {
if (s.length() == 0)
return 0;
int maxLen = 0;
int[] d = new int[s.length()];
// d[i] means substring starts with i has max valid lenth of d[i]
d[s.length() - 1] = 0;
for (int i = s.length() - 2; i >= 0; i--) {
if (s.charAt(i) == ')')
d[i] = 0;
else {
int j = (i + 1) + d[i + 1];
if (j < s.length() && s.charAt(j) == ')') {
d[i] = d[i + 1] + 2; //(()())的外包情况
if (j + 1 < s.length())
d[i] += d[j + 1];//()()的后面还有的情况
}
}
maxLen = Math.max(maxLen, d[i]);
}
return maxLen;
}