Leetcode longest Valid parentheses

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

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

Test instructions: Find the length of the longest legal string

Idea: DP thought, with D[I] to indicate the length of the match from the first position, then for the first I, if it is the right parenthesis, then this position is 0, if it is to do the parentheses, then skip the first i+1 match the longest length of the position to J, see position J is not the right parenthesis, The second is to add the matching length of position j+1.

Class Solution {public:    int longestvalidparentheses (string s) {        if (s.length () = = 0) return 0;        int ans = 0;        int *d = new Int[s.length ()];        for (int i = 0; i < s.length (); i++)            d[i] = 0;        D[s.length ()-1] = 0;        for (int i = S.length ()-2; I >= 0; i--) {            if (s[i] = = ') ')                 d[i] = 0;            else {                Int j = i + 1 + d[i + 1];                if (J < s.length () && s[j] = = ') ') {                    d[i] = d[i+1] + 2;                    if (j + 1 < S.length ())                         d[i] + = d[j+1];}            }            ans = max (ans, d[i]);        }        return ans;    };



Leetcode 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.