# "Leetcode" longest Valid parentheses

Source: Internet
Author: User

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

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

Dp[i] Indicates the length of the longest valid pair of parentheses, starting from s[i] (including S[i]) and reaching s[n-1]. If s[i]== ' (' We need to check if the parentheses of the j=dp[i+1]+i+1 corresponding s[j] position are "), if S[J] is ') ' then the parentheses are formed, so dp[i]=dp[i+1]+2 at the same time, we need to continue to consider dp[j+1] If the j+1 is not out of range, then dp[i]=dp[i+1]+2+dp[j+1] other conditions dp[i]=0;
`1 classSolution {2  Public:3     intLongestvalidparentheses (strings) {4         intn=s.length ();5         if(n==0)return 0;6        7         int*dp=New int[n];8dp[n-1]=0;9        Ten         intresult=0; One          for(inti=n-2; i>=0; i--) A         { -             if(s[i]=='(') -             { the                 intj=dp[i+1]+i+1; -                 -                 if(s[j]==')') -                 { +dp[i]=dp[i+1]+2; -                     if(j<n-1) dp[i]+=dp[j+1]; +                 } A                 Else at                 { -dp[i]=0; -                 } -                 -                 if(dp[i]>result) -                 { inresult=Dp[i]; -                 } to             } +             Else -             { thedp[i]=0; *             } \$         }Panax Notoginseng Delete [] DP; -         returnresult; the     } +};`

"Leetcode" longest Valid parentheses

Related Keywords:

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.