Given A string containing just the characters ‘(‘ ‘)‘ and, find the length of the longest valid (well-formed) parenthe SES substring.
for " (() ", the longest valid parentheses substring is " () ", which has length = 2.
Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.
Test instructions: Find the length of the longest legal string
Idea: DP thought, with D[I] to indicate the length of the match from the first position, then for the first I, if it is the right parenthesis, then this position is 0, if it is to do the parentheses, then skip the first i+1 match the longest length of the position to J, see position J is not the right parenthesis, The second is to add the matching length of position j+1.
Class Solution {public: int longestvalidparentheses (string s) { if (s.length () = = 0) return 0; int ans = 0; int *d = new Int[s.length ()]; for (int i = 0; i < s.length (); i++) d[i] = 0; D[s.length ()-1] = 0; for (int i = S.length ()-2; I >= 0; i--) { if (s[i] = = ') ') d[i] = 0; else { Int j = i + 1 + d[i + 1]; if (J < s.length () && s[j] = = ') ') { d[i] = d[i+1] + 2; if (j + 1 < S.length ()) d[i] + = d[j+1];} } ans = max (ans, d[i]); } return ans; };
Leetcode longest Valid parentheses