括号匹配

一、有效的括号匹配

 题目描述: 

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

  有效字符串需满足:

   左括号必须用相同类型的右括号闭合。

   左括号必须以正确的顺序闭合。

  注意空字符串可被认为是有效字符串

 思路:

  遍历每个字符,左括号的话就如栈,是右括号的话就将栈中的配对括号出栈,最后栈应该为空值

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 != 0:
            return False
        dict_ = { '(':')', '[':']', '{':'}' }
        temp = []
        for each in s:
            if each in dict_:
                temp.append(each)
            else:
                if not temp or dict_[ temp[-1] ]  != each:
                    return False
                else:
                    temp.pop()
        return (not temp)

  

原文地址:https://www.cnblogs.com/always-fight/p/10287080.html