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 “()()”
class Solution {
public int longestValidParentheses(String s) {
int l = s.length();
if(l < 2) {
return 0;
}
int[] dp = new int[l + 1];
// if s[i - 1] == ")",left = i - 2 - dp[i -1]
// if s[left - 1] = "(" dp[i] = dp[i - 1] + 2;
// if left >0 dp[i] =dp[i] + dp[left -1];
int max = 0;
for(int i = 1; i <= l ;i++ ) {
if(s.charAt(i - 1) == ')') {
int left = i - dp[i - 1] - 1;
if(left < 1) {
continue;
}
if(s.charAt(left - 1) != '(') {
continue;
}
dp[i] = dp[i - 1] + 2;
dp[i] = dp[i] + dp[left - 1];
max = Math.max(max, dp[i]);
}
}
return max;
}
}