"Stack" longest Valid parentheses

Source: Internet
Author: User

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

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.