Longest Valid parentheses

Source: Internet
Author: User

Eliminate all valid parentheses, that is, a pair (), and use buyers to save the invalid parentheses in a single (or) subscript in a string. Then the difference between each of the two illegal subscript minus 1 is the length of the legal string in the middle, followed by a backward comparison, to select the largest string.

1 classSolution {2  Public:3     intLongestvalidparentheses (strings) {4stack<int>St;5      intN=s.length (), a,b,longest=0;6       for(intI=0; i<n;i++)7      {8          if(s[i]=='(') St.push (i);9          Else if(!st.empty ())//When the buyers is empty, its top is 0, so determine if it is emptyTen          { One           if(S[st.top ()]=='(') St.pop (); A              ElseSt.push (i); -          } -          ElseSt.push (i); the           -      } -A=N; -b=0; +      if(St.empty ()) longest=N; -      Else  +      { A           while(!st.empty ()) at          { -b=st.top (); St.pop (); -Longest=max (longest,a-b-1); -A=b; -          } -longest=Max (longest,a); in      } -      returnlongest; to     } +};

The following is a dynamic programming approach:

Each longest represents the most effective length of this segment, which is divided by ') '

1 classSolution {2  Public:3     intLongestvalidparentheses (strings) {4         intn=s.length ();5         intMaxvalid=0;6vector<int> Longest (N,0);7        for(intI=1; i<n;i++)8       {9           if(s[i]==')')Ten           { One               if(s[i-1]=='(') A               { -longest[i]= (I-2) >=0? (longest[i-2]+2):2; -Maxvalid=Max (maxvalid,longest[i]); the               } -               Else if((i-longest[i-1]-1) >=0&&s[i-longest[i-1]-1]=='('//i-longest[i-1]-1 is to seek this ' (' corresponding ' (' position -               { -longest[i]=longest[i-1]+2+ ((i-longest[i-1]-2>=0)? longest[i-longest[i-1]-2]:0); Note that the last curly brace cannot be lost!!  +Maxvalid=Max (maxvalid,longest[i]); -               } +           } A       } at       returnMaxvalid; -     } -};

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.