【每日一题Leetcode】Valid Parentheses

继续搬https://zhuanlan.zhihu.com/p/36414513

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.
  3. Note that an empty string is also considered valid


这个刚开始想的太复杂了,大至记录下思考过程:

1 .检查是否空字符串

2. 检查len是否偶数,否则肯定不成对。

3. 检查首尾括号的开口方向

4. 从中间位置二分,检查两边是否能组对。这个实际上有点麻烦,因为除了检查左右对比还需要检查分开的两个子串。

5. 参考论坛贴子后,决定采用stack的思路。简单理解就是,前进后出的原则给左括号配对。



class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
                
        str_dict = {')':'(',']':'[','}':'{'}
        stack = []
        
        if len(s) == 0:  #判断是否空串
            return True       
        #检查是否成对以及是否首尾括号方向正确
        if len(s)%2 != 0 or s[0] in str_dict.keys() or s[-1] in str_dict.values():
            return False
            
        for i in range(len(s)):
                
            if s[i] in str_dict.values() and i < len(s):
                stack.append(s[i])
                    
                
            elif str_dict[s[i]] != stack[-1]:
                return False
                
            else:
                del stack[-1]                    
                     
      
        return True
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值