Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
My code:
import numpy as np
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
self.record=np.zeros([len(s),len(s)])-1
count,flag=self.Find_result(s,0,len(s)-1)
return count
def Find_result(self,s,i,j):
if i>j:
return 0,True
if i==j:
return 0,False
if self.record[i,j]!=-1:
flag=False
if j-i+1==self.record[i,j]:
flag=True
return self.record[i,j],flag
if j-1==i and s[j]==')' and s[i]=='(':
self.record[i,j]=2
return 2,True
if s[i]=="(" and s[i+1]==")" and i+1<=j:
result1,flag1=self.Find_result(s,i+2,j)
if flag1:
self.record[i,j]=result1+2
return result1+2,flag1
if s[j]=="(" and s[j-1]==")" and j-1>=i:
result1,flag1=self.Find_result(s,i,j-2)
if flag1:
self.record[i,j]=result1+2
return result1+2,flag1
if s[i]=="(" and s[j]==")":
count1,flag1=self.Find_result(s,i+1,j-1)
if flag1:
self.record[i,j]=count1+2
return count1+2,flag1
result1,flag1=self.Find_result(s,i+1,j)
result2,flag2=self.Find_result(s,i,j-1)
if result1>result2:
self.record[i,j]=result1
return result1,False
else:
self.record[i,j]=result2
return result2,False
Solution:
https://leetcode.com/problems/longest-valid-parentheses/
Code in O(n):
import numpy as np
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
#self.record=np.zeros([len(s),len(s)])-1
#count,flag=self.Find_result(s,0,len(s)-1)
stack=[]
count=0
stack.append(-1)
for i in range(len(s)):
if s[i]=="(":
stack.append(i)
if s[i]==")":
stack.pop(-1)
if len(stack)==0:
stack.append(i)
else:
if count<i-stack[-1]:
count=i-stack[-1]
return count