Leetcode 20. 有效的括号 Python

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

自己加了注释,欢迎讨论。推荐看上面链接的视频,思路非常清晰。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值