Title: Leetcode
Longest Valid parentheses
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 "()()" are, which has length = 4.
Analysis:
1, first scan from left to right. Encountered ' (' then into the stack, and vice versa. updates the return value one time whenever the stack is empty res! Because the maximum value has been reached at this time.
2, then scan from right to left. Why do I need to scan from right to left? Since the end of the scan from left to right, if the stack is not empty, then it is possible that a portion of the valid left parenthesis is not recorded in the Res.
int longestvalidparentheses (string s) {if (S.size () <2) return 0; int res=0,cur=0; Stack<char> sa; for (int i=0;i<s.size (); i++) {if (s[i]== ' (') {Sa.push (s[i]); cur++; } else {if (Sa.empty ()) {Res=max (res,cur); cur=0; } else {sa.pop (); cur++; if (Sa.empty ()) Res=max (res,cur); }}} if (Sa.empty ()) return res; while (!sa.empty ()) {Sa.pop (); } cur=0; for (int i=s.size () -1;i>=0;i--) {if (s[i]== ') ') {Sa.push (s[i]); cur++; } else { if (Sa.empty ()) {Res=max (res,cur); cur=0; } else {sa.pop (); cur++; if (Sa.empty ()) Res=max (res,cur); }}} return res; }
"Stack" longest Valid parentheses