22. Generate Parentheses
dfs stack
思路:
If you have two stacks, one for n "(", the other for n ")", you generate a binary tree from these two stacks of left/right parentheses to form an output string.
This means that whenever you traverse deeper, you pop one parentheses from one of stacks. When two stacks are empty, you form an output string.
How to form a legal string? Here is the simple observation:
- For the output string to be right, stack of ")" most be larger than stack of "(". If not, it creates string like "())"
- Since elements in each of stack are the same, we can simply express them with a number. For example, left = 3 is like a stacks ["(", "(", "("]
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
left, right, res = n, n, []
self.dfs(left, right, res, "")
return res
def dfs(self, left, right, res, cur):
if left > right:
return
if not left and not right:
res.append(cur)
if left:
self.dfs(left-1, right, res, cur+'(')
if right:
self.dfs(left, right-1, res, cur+')')
678. Valid Parenthesis String
思路:
The number of open parenthesis is in a range [cmin, cmax]
cmax
counts the maximum open parenthesis, which means the maximum number of unbalanced '(' that COULD be paired.cmin
counts the minimum open parenthesis, which means the number of unbalanced '(' that MUST be paired.
The string is valid for 2 condition:
cmax
will never be negative.cmin
is 0 at the end.
stackmin 存的是最少的 ( 还未匹配的个数, stackmax是最多的个数。 为什么有最多和最少? 把* 当做 (,stackmax 就要加1,把* 当做)的时候-1
class Solution(object):
def checkValidString(self, s):
smin = smax = 0
for c in s:
if c == '(':
smin += 1
smax += 1
elif c == ')':
smax -= 1
smin = max(smin-1, 0)
elif c == '*':
smax += 1
smin = max(smin-1, 0)
if smax < 0:
return False
return smin == 0
32. Longest Valid Parentheses
这个article写得很好, 这种括号的一般都可以用stack来做
https://leetcode.com/articles/longest-valid-parentheses/
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
# left right O(n) O(1)
n = len(s)
maxLen = 0
left = right = 0
for i in xrange(n): # 从左往右
if s[i] == '(':
left += 1
elif s[i] == ')':
right += 1
if left == right:
maxLen = max(maxLen, left*2)
if right > left:
left = right = 0
left = right = 0
for i in xrange(n-1, -1, -1): # 从右往左 重复
if s[i] == '(':
left += 1
elif s[i] == ')':
right += 1
if left == right:
maxLen = max(maxLen, left*2)
if right < left: # 反过来
left = right = 0
return maxLen