给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
把对应的括号存到字典里,用一个辅助栈帮助处理,遇到一对就弹出。最后判断辅助栈剩余是否为空。
今天发现 for c in dic这个遍历字典只找了键,我以前还是写的 for c in dic.keys()
class Solution:
def isValid(self, s: str) -> bool:
dic = {'(':')','[':']','{':'}','?':'?'} #多存一个问号为了下面栈里存的问号在dic[stack.pop()]时不报错
stack=['?'] #多存一个问号为了避免stack.pop()报错
for ss in s:
if ss in dic:
stack.append(ss)
elif dic[stack.pop()]!=ss:
return False
return len(stack)==1 #最后剩初始那个问号
代码来源:作者:jyd 链接:https://leetcode-cn.com/problems/valid-parentheses/solution/valid-parentheses-fu-zhu-zhan-fa-by-jin407891080/
直接这样写的话就不用在字典里存{'?':'?'}了
class Solution:
def isValid(self, s: str) -> bool:
dic = {'(':')','[':']','{':'}'}
stack = ['?']
for ss in s:
if ss in dic:
stack.append(dic[ss])
elif ss!=stack.pop():
return False
return len(stack)==1
把字典反过来存的话,if else也反一下:
class Solution:
def isValid(self, s: str) -> bool:
dic = {']':'[','}':'{',')':'(','?':'?'}
stack = ['?']
for c in s:
if c in dic:
if stack[-1]!=dic[c]:
return False
else:
stack.pop()
else:
stack.append(c)
return len(stack)==1
官方解答就是反过来的,不过stack.pop()加了个判断stack是否为空,就不用那个初始问号了。
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
作者:LeetCode 链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/
来源:力扣(LeetCode)