Leetcode20. 有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
left = ['(', '[', '{']
right = [')', ']', '}']
stack =[]
for i in s:
if i in left:
stack.append(i)
elif i in right:
if len(stack) > 0:
ss = stack.pop()
if not((ss == '(' and i == ')') or (ss == '[' and i == ']') or (ss == '{' and i == '}')):
return False
else:
return False
else:
return False
if len(stack) != 0:
return False
return True
Leetcode22.括号生成
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
# 回溯法
# 如果我们还剩一个位置,我们可以开始放一个左括号。 如果它不超过左括号的数量,我们可以放一个右括号。
res = []
def backtrack(s = '', left = 0, right = 0):
if len(s) == 2 * n:
res.append(s)
return
if left < n:
backtrack(s + '(', left+1, right)
if right < left:
backtrack(s + ')', left, right+1)
backtrack()
return res