LeetCode Longest Valid Parentheses

Source: Internet
Author: User

LeetCode Longest Valid Parentheses
LeetCode Longest Valid Parentheses

Original question

Find the length of the longest valid substring that only contains "(" and. Valid means that the parentheses in the substring can be correctly matched.

Note:

Note that empty strings

Example:

Input: s = "()"
Output: 2

Input: s = ") ()"
Output: 4

Solutions

Dynamic Planning is adopted. dp [I] indicates the maximum length at the end of the substring with I. The final result is the maximum value in dp. If it is not a Null String, dp [0] = 0, because a bracket cannot match correctly. The recursive relationship is:

) ( ) ( ( ) ) )0 1 2 3 4 5 6 7

Check the matching of the first brace in the current brace. For example, the best match ending with 6 before 7 is 3-6. Check whether the brackets before 3 match with 7, if it does not match, it does not change. The best match ending with 5 before 6 is 4-5. When 3 and 6 match, dp [I] + 2. In addition, if the dp value of the parentheses before the left parentheses matching the current parentheses should also be added, because the current parentheses are added and those parentheses are also connected. For example, after 3 and 6 match, 1 and 2 should also be added to the best match ending with 6.

AC Source Code
class Solution(object):    def longestValidParentheses(self, s):        """        :type s: str        :rtype: int        """        if not s:            return 0        length = len(s)        dp = [0 for __ in range(length)]        for i in range(1, length):            if s[i] == ")":                j = i - 1 - dp[i - 1]                if j >= 0 and s[j] == "(":                    dp[i] = dp[i - 1] + 2                    if j - 1 >= 0:                        dp[i] += dp[j - 1]        return max(dp)if __name__ == "__main__":    assert Solution().longestValidParentheses("(()))())(") == 4    assert Solution().longestValidParentheses("(()") == 2    assert Solution().longestValidParentheses(")()())") == 4

 

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.