有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([)]”
输出:false
示例 5:
输入:s = “{[]}”
输出:true
来源:力扣(LeetCode) 20
我的答案:
class Solution:
def isValid(self, s: str) -> bool:
#如果字符串长度是单数或者0的话直接返回False
if len(s) == 0 or len(s) % 2 == 1:
return False
#定义一个列表挨个接收字符串
list=[]
#遍历s字符串
for i in range(0,len(s)):
#如果list列表是空的话直接压入当前字符
if len(list) == 0:
list.append(s[i])
#如果当前字符与列表中的最后一个字符能匹配上,压出list的最后一个字符
elif list[len(list) - 1] == '(' and s[i] == ')':
list.pop()
elif list[len(list) -1] == '[' and s[i] == ']':
list.pop()
elif list[len(list) -1] == '{' and s[i] == '}':
list.pop()
else:
list.append(s[i])
#如果list是空的话说明每一个压入的字符都匹配上了,返回True,否则返回False
if len(list) == 0:
return True
else:
return False
结果:
执行结果:通过
执行用时:28 ms, 在所有 Python3 提交中击败了89.53%的用户
内存消耗:14.7 MB, 在所有 Python3 提交中击败了96.42%的用户
通过测试用例:91 / 91
大佬答案:
运用了栈的思想(和我的一样,嘿嘿)
class Solution:
def isValid(self, s: str) -> bool:
#创建字典将括号对应起来
dic = {')':'(',']':'[','}':'{'}
#定义列表stack来接收字符串
stack = []
#遍历字符串
for i in s:
#当stack 不为空且i为右括号“)”或“]”或“}”时判断i是否与栈中最后一个元素相匹配
#若匹配,栈中左括号出栈,不匹配的话,继续压入栈中
#i in dic表示i为右括号为真
if stack and i in dic:
if stack[-1] == dic[i]: stack.pop()
else: return False
else: stack.append(i)
return not stack