Longest Valid parentheses
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.
Problem Solving Ideas:
Test instructions finds the length of the substring of the longest valid parenthesis. The biggest problem, the first idea is dynamic planning, but the formula is really not easy to find. Hi Brush http://bangbingsyb.blogspot.jp/2014/11/leetcode-longest-valid-parentheses.html has the relevant instructions, I do not understand,.
Due to the problem of parentheses, it can be implemented using stacks. This is different from judging whether the stack is effective. Notice that if a closing parenthesis does not match one of the preceding opening brackets, the closing parenthesis can be split as a substring. The general idea is that if you encounter an opening parenthesis, you unconditionally place the subscript of the left parenthesis into the stack. If a closing parenthesis is encountered, if the top of the stack is matched with an opening parenthesis, the left parenthesis is stacked and the maximum length value is updated. If there is no left parenthesis at the top of the stack to match, enclose the right parenthesis in the stack as a split character. The code is as follows:
Class Solution {public: int longestvalidparentheses (string s) { int len=s.length (); Stack<int> St; int maxlen=0; for (int i=0; i<len; i++) { if (s[i]== ' (') { st.push (i); } else{ if (!st.empty () &&s[st.top ()]== ' (') { st.pop (); MaxLen = Max (MaxLen, St.empty ()? I+1:i-st.top ()); } else{ St.push (i); }} return maxlen;} ;
[Leetcode] Longest Valid parentheses