LeetCode: Longest Valid Parentheses

Source: Internet
Author: User

Given a string containing just the characters'('And')', Find

Length of the longest valid (well-formed) parentheses substring."(()",

Longest valid parentheses substring is"()", Which has length = 2.

Another example is")()())", Where the longest valid parentheses substring

Is"()()", Which has length = 4.


Solution:

You can use the stack or dp to solve this problem, but the O (N) solution written by the stack is not faster than dp. So let's talk about the dp idea.

First, let's look at the definition of the status:

Dp [I]: the maximum number of valid parentheses that can be composed of the I-th character.Through the above State definition, it is easy to get the following state transition equation:


The second state equation is obtained. When s [I] = ") ', tmp indicates the character corresponding to s [I ].
(Tmp> = 0 & s [tmp] = '(') indicates that tmp to I is a valid matching of parentheses, effective brackets may exist before tmp.
Configuration, so you need to add the two. Note that the boundary is located.
Solution code:
class Solution {public:    int longestValidParentheses(string s)     {        int n = s.size(), dp[n];        dp[0] = 0;        for (int i = 1; i < n; ++i)        {            int tmp = i - 1 - dp[i - 1];            if (s[i] == '(')                dp[i] = 0;            else if (tmp >= 0 && s[tmp] == '(')                dp[i] = dp[i - 1] + 2 + (tmp - 1 >= 0 ? dp[tmp - 1] : 0);            else                dp[i] = 0;        }        return *max_element(dp, dp + n);    }};


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.