defisValid(self,s:str) ->bool: dic ={')':'(',']':'[','}':'{'} stack = []for c in s:if c in dic: left ='#'ifnot stack else stack.pop()if left != dic[c]:returnFalseelse: stack.append(c)returnnot stack
678. Valid Parenthesis String
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
An empty string is also valid
"""Count the lower bound and higher bound of left bracketIf higher bound < 0, means it can't be valid in current position and afterwardCheck if lower bound == 0 when return"""defcheckValidString(self,s:str) ->bool: lo, hi =0,0for c in s: lo +=1if c =='('else-1 hi +=1if c in'(*'else-1if hi <0:returnFalseif lo <0: lo =0return lo ==0
22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
n =3["((()))","(()())","(())()","()(())","()()()"]
defgenerateParenthesis(self,n:int) -> List[str]: ans = []defbacktracking(s,left,right):iflen(s)==2*n: ans.append(s)returnif left < n:backtracking(s+'(', left+1, right)if right < left:backtracking(s+')', left, right+1)backtracking('', 0, 0)return ans
32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
dp
State: dp[i], s[:i+1]的LVP
Tran: only consider s[i] == ')',
dp[i] = dp[i-2] + 2 if s[i-1] == '('
dp[i] = dp[i-dp[i-1]-1] + 2 if s[i-1] = ')'
+ dp[i-dp[i-1]-2] if i-dp[i-1]-2 >= 0
deflongestValidParentheses(self,s:str) ->int: dp = [0] *len(s) ans =0for i inrange(1, len(s)):if s[i]==')':if s[i-1]=='(': dp[i]=2+ (dp[i-2]if i-2>=0else0)elif i-dp[i-1]-1>=0and s[i-dp[i-1]-1]=='(': dp[i]=2+ dp[i-1]if i-dp[i-1]-2>=0: dp[i]+= dp[i-dp[i-1]-2] ans =max(ans, dp[i])return ans
List double end traverse
There are only three cases for a string:
'(' are more than ')'
'(' are less than ')'
'(' and ')' are the same
Now, when you scan from left to right, you can only find the correct maxLength for cases 2 and 3, because if it is case 1, where '(' are more than ')' (e.g., "((()"), then left is always greater than right and maxLength does not have the chance to be updated.
deflongestValidParentheses(self,s:str) ->int: left, right =0,0 ans =0for c in s:if c =='(': left+=1else: right+=1if left == right: ans =max(ans, right*2)elif right > left: left, right =0,0 left, right =0,0for c in s[::-1]:if c =='(': left+=1else: right+=1if left == right: ans =max(ans, right*2)elif left > right: left, right =0,0return ans
1190. Reverse Substrings Between Each Pair of Parentheses
You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Input: s ="(abcd)"Output:"dcba"
Time: O(n^2), Space: O(n)
defreverseParentheses(self,s:str) ->str: line ='' stack = []for c in s:if c =='(': stack.append(line) line =''elif c ==')': pre = stack.pop() pre += line[::-1] line = preelse: line += creturn line
Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.
defminAddToMakeValid(self,S:str) ->int: balance =0 count =0for c in S: balance +=1if c =='('else-1# right bracket is greater, must add a left bracketif balance ==-1: count +=1 balance =0# rest of left bracketsreturn count + balance
1249. Minimum Remove to Make Valid Parentheses
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, contains only lowercase characters, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
""" record the index should be removed and rebuild the string """defminRemoveToMakeValid(self,s:str) ->str: stack = [] # record left parentheses to remove remove =set()# record right parenthesese to removefor i, c inenumerate(s):if c notin'()':continueif c =='(': stack.append(i)# "))((" 的情況elif c ==')'andnot stack: remove.add(i)else: stack.pop() remove = remove.union(set(stack)) build =''for i inrange(len(s)):if i notin remove: build += s[i]return build
301. Remove Invalid Parentheses
example
Input: "()())()"
Output: ["()()()", "(())()"]
先計算 需要remove 多少 '(' and ')'
Backtracking, 適當剪支, 符合條件加入答案(利用set, 因為可能重複)
defremoveInvalidParentheses(self,s:str) -> List[str]:# count invalid '(' and ')' left, right =0,0for c in s:if c =='(': left +=1elif c ==')':if left ==0: right +=1else: left -=1 self.ans =set() self.dfs(s, 0, 0, 0, left, right, '')returnlist(self.ans)defdfs(self,s,idx,l,r,left_rem,right_rem,exp):if idx ==len(s):if left_rem == right_rem ==0: self.ans.add(exp)return c = s[idx]# ignore c either keep c 分開討論if c =='(': self.dfs(s, idx+1, l+1, r, left_rem, right_rem, exp+c)if left_rem >0: self.dfs(s, idx+1, l, r, left_rem-1, right_rem, exp)elif c ==')':# prune, 只有 r < l 才進行 recursionif l > r: self.dfs(s, idx+1, l, r+1, left_rem, right_rem, exp+c)if right_rem >0: self.dfs(s, idx+1, l, r, left_rem, right_rem-1, exp)# c is letter else: self.dfs(s, idx+1, l, r, left_rem, right_rem, exp+c)