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: