Given a string containing just the characters'('And')', Find
Length of the longest valid (well-formed) parentheses substring."(()",
Longest valid parentheses substring is"()", Which has length = 2.
Another example is")()())", Where the longest valid parentheses substring
Is"()()", Which has length = 4.
Solution:
You can use the stack or dp to solve this problem, but the O (N) solution written by the stack is not faster than dp. So let's talk about the dp idea.
First, let's look at the definition of the status:
Dp [I]: the maximum number of valid parentheses that can be composed of the I-th character.Through the above State definition, it is easy to get the following state transition equation:
The second state equation is obtained. When s [I] = ") ', tmp indicates the character corresponding to s [I ].
(Tmp> = 0 & s [tmp] = '(') indicates that tmp to I is a valid matching of parentheses, effective brackets may exist before tmp.
Configuration, so you need to add the two. Note that the boundary is located.
Solution code:
class Solution {public: int longestValidParentheses(string s) { int n = s.size(), dp[n]; dp[0] = 0; for (int i = 1; i < n; ++i) { int tmp = i - 1 - dp[i - 1]; if (s[i] == '(') dp[i] = 0; else if (tmp >= 0 && s[tmp] == '(') dp[i] = dp[i - 1] + 2 + (tmp - 1 >= 0 ? dp[tmp - 1] : 0); else dp[i] = 0; } return *max_element(dp, dp + n); }};