leetcode 20. Valid Parentheses

有效的括号
valid parentheses

题目:
Given a string s containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. (相同类型)
Open brackets must be closed in the correct order. (正确的顺序)

在这里插入图片描述

这道题:堆栈的思维
先进后出,要配成对

误区:1) 最开始我没有看懂题,认为 ([)也是对的,但是不是的,是需要配好对。应该用堆栈。
2) 括号只有这三种,“(”," [", " {", 所以这三个肯定是要遍历的。

把括号一切左边的部分都压入到堆栈中,用右边的来匹配。

   class Solution:
def isValid(self, s: str) -> bool:
    if len(s)==0:
        return True   
    stack=[]
     for c in s:

        if c=='(' or c=='[' or c=='{':
            stack.append(c)
        else:
            if len(stack)==0:
                return False
            else:

                d=stack.pop()
                if c == ')' and d!='(':
                    return False
                elif c ==']' and d!='[':
                    return False
                elif c =='}' and d!='{':
                    return False
            
    if len(stack)!=0:
        return False
    else:
        return True

这是一个easy的题,但是我遇到了很多问题。
(1)len(s)=0 是true的,但是我没有考虑到
(2)若list是空,pop()会出错。
(3) if c == ‘)’ and d!=’(’, 则return False。但是最开始我写的是:
if c == ‘)’ and d==’(’, 写的很不顺利。
(4)忘记了len(stack) 不为空的情况。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值