Leetcode 20. 有效的括号 Python
题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
自己解法
删掉所有挨在一起的() [] {},如果最后字符串为空则判对,否则判错。
思路跟下一样,但是不知道字符串的replace方法,浪费了不少时间
http://www.runoob.com/python/att-string-replace.html
**replace可以起到删除指定字符的作用!!**这个在网上bd查了好久查不到…
class Solution:
def isValid(self, s):
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''
美丽的官方解答
https://leetcode-cn.com/articles/valid-parentheses/
有视频讲解,讲的很棒,要用栈的思路去思考。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
dt = {'(':')','{':'}','[':']'}
#字典存储
# Taken another local storage to avoid iterating through keys for each character in string
dtk = dt.keys()#键
for c in s:#c是s中的字符
#If it is open paranthesis then PUSH to stack
if c in dt.keys():#如果c在字典dt的键里,就加到栈中
stack.append(c)
#If it is closed paranthesis then pop from stack and compare with current closed paranthesis
elif stack: #如果c不在dt的键里,且栈不为空
if dt[stack.pop()] != c: #只要栈顶元素不是键对应的值,就判错
return False
# This case is when a single open closed paranthesis is present
else: #如果c不在dt的键里,且栈为空,自动判错
return False
# if no characters remaining in string and still stack is not empty then given string is not valid
if stack: #最后只有空栈才能判对
return False
else:
return True
自己加了注释,欢迎讨论。推荐看上面链接的视频,思路非常清晰。