Valid Parentheses/easy/day5

题目:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

我的做法:

 def isValid(self, s):
        d = dict([('(', ')'),('[', ']'),('{','}')])
        a = []
        for i in s:
            if a and a[-1] in d.keys() and d[a[-1]] == i:
                a.pop()
            else:
                a.append(i)
        if a:
            return False
        else:
            return True

    

参考:

  deq = deque()
        pair = {'(': ')', '[': ']', '{': '}'}
        for letter in s:
            if letter == '(' or letter == '[' or letter == '{':
                deq.append(letter)
            else:
                if len(deq) > 0 and letter == pair[deq[-1]]:
                    deq.pop()
                else:
                    return False   

        return len(deq) == 0

知识点:

python用pop 和append实现堆栈

python---创建字典的方式

1、用{}创建字典   x = {"a":"1", "b":"2"}

2、用内置函数dict()

    x = dict(a="1", b="2")

   x = dict((("a", "1"), ("b", "2")))    //元祖内元祖,列表内列表,元祖内列表,列表内元祖都ok


--------------新手刷题,仅用于自身记录,如有错误,欢迎指出---------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值