Permalink
Cannot retrieve contributors at this time
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?
LeetCode/Longest Valid Parentheses
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
91 lines (82 sloc)
2.57 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |