判断括号是否成对

示例:

输入:"()"   输出:True

输入:"()[]{}"  输出:True

输入:"(]"    输出:False

输入:"([)]"   输出:Fasle

输入:"{[]}"    输出:True

Python解决方案:

利用栈解决

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return True
        stack = []
        par = {")":"(","]":"[","}":"{"}
        for i in s:
            if not stack or i not in par:
                stack.append(i)
            else:
                if stack.pop() != par[i]:
                    return False
        return not stack
原文地址:https://www.cnblogs.com/wenqinchao/p/10606765.html