每日leetcode:括号匹配

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
3.注意空字符串可被认为是有效字符串。

很明显的用栈解决,但是怎么实现?

最笨的办法也是最直接的办法:自己写一个栈,然后在遇到(,{,[时3入栈,否则出栈与当前字符对比,不匹配则返回false,当栈为空而字符串还没读完或者字符串读完栈仍然不为空时返回false,否则返回true。

    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    def isValid(self, s: str) -> bool:
        def pop(stack):
            if stack.next == None:
                return False
            ret = stack.next.val
            stack.next = stack.next.next
            return ret
        def push(stack, c):
            newNode = ListNode(c)
            newNode.next = stack.next
            stack.next = newNode
        def create():
            stack = ListNode(" ")
            return stack
        stack = create()
        for c in s:
            if c == "(":
                push(stack, "(")
            elif c == "{":
                push(stack, "{")
            elif c == "[":
                push(stack, "[")
            elif c == ")":
                temp = pop(stack)
                if temp != "(":
                    return False
            elif c == "}":
                temp = pop(stack)
                if temp != "{":
                    return False
            elif c == "]":
                temp = pop(stack)
                if temp != "[":
                    return False            
        if stack.next != None:
            return False
        else:
            return True

 

这样的效率很低,用了68ms,速度快于55.24%的人。

优化的方法是:python自带的数据结构List可以实现栈的功能,事实上,线性表的功能如栈、队列等都能用List进行实现。

    def isValid(self, s: str) -> bool:
        stack = []
        dic = {
            ")" : "(",
            "}" : "{",
            "]" : "[" 
        }
        for c in s:
            if c == "(" or c == "{" or c == "[":
                stack.append(c)
            else:
                pop = dic[c]
                if len(stack) == 0 or stack[-1] != pop:
                    return False
                else:
                    stack.pop()
        if len(stack) != 0:
            return False
        else:
            return True

用时48ms,击败了94.6%的用户,但是这里的 if c == "(" or c == "{" or c == "[": 明显可以继续优化,因为这几个符号都是字典的key,字典有专门的检查是否有某个key的操作,还有就是len(stack)==0的判断方法可以直接用stack进行代替,还有就是要注意,这里在第一个else后面之所以不直接pop=stack.pop(),是因为可能stack已经为空,所以不能直接进行pop,考虑到后面还判断了stack是否为空,这里没有必要进行这样的特殊处理:

    def isValid(self, s: str) -> bool:
        stack = []
        dic = {
            "(" : ")",
            "{" : "}",
            "[" : "]"
        }
        for c in s:
            if c in dic:
                stack.append(c)
                continue
            elif stack and dic[stack[-1]] == c:
                    stack.pop()
            else:
                return False
        if stack:
            return False
        else:
            return True

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值