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.
class Solution { public: int longestValidParentheses(std::string s) { int dp[1000005], i, max = 0; memset(dp, 0, sizeof(dp)); for(i = 1; i < s.size(); i++) { if(s[i] != ')' || s[i-dp[i]-1] != '(') continue; dp[i+1] = 2 + dp[i] + dp[i-dp[i]-1]; if(dp[i+1] > max) max = dp[i+1]; } return max; } };