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