[Leetcode] Longest Valid parentheses maximum effective bracket

Source: Internet
Author: User

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 "()" are, which has length = 2.

Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.

This is the longest effective parenthesis than the previous Valid parentheses to verify the parentheses more difficult, here we still use the stack to solve, we need to define a start variable to record the starting position of the legal bracket string, we traverse the string, if we encounter an opening parenthesis, the current subscript is pressed into the stack, If a closing parenthesis is encountered, if the current stack is empty, the next coordinate position is recorded to start, and if the stack is not empty, the top element of the stack is taken out, and if the stack is empty, the result is updated and the larger value in I-start + 1 is updated, otherwise the result and the large values in the I-stack top element are as follows

classSolution { Public:    intLongestvalidparentheses (strings) {intres =0, start =0; Stack<int>m;  for(inti =0; I < s.size (); ++i) {if(S[i] = ='(') M.push (i); Else if(S[i] = =')') {                if(M.empty ()) start = i +1; Else{m.pop (); Res= M.empty ()? Max (res, I-start +1): Max (res, I-m.top ()); }            }        }        returnRes; }};

There is also a method of dynamic programming programming, which can be found in the blog of user's favorite brush.

[Leetcode] Longest Valid parentheses maximum effective bracket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.