LeetCode #32: Longest Valid Parentheses

来源:互联网 发布:java递归获取子节点 编辑:程序博客网 时间:2024/06/05 14:41

Problem Statement

(Source) Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

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

Solution

class Solution(object):    def longestValidParentheses(self, s):        """        :type s: str        :rtype: int        """        n = len(s)        if n < 2:            return 0        res = 0        dp = [0 for i in xrange(n + 1)]        for i in xrange(2, n + 1):            if s[i- 1] == ')':                if s[i - 2] == '(':                    dp[i] = dp[i - 2] + 2                else:                    left = i - 1 - dp[i - 1]                    if left >= 1 and s[left - 1] == '(':                        dp[i] = dp[left - 1] + dp[i - 1] + 2            res = max(res, dp[i])        return res

Complexity analysis
- Time complexity: O(n), where n is the length of input string.
- Space complexity: O(n), where n is the length of input string.

0 0
原创粉丝点击