Python实现“有效的括号”的两种方法

给定包含'(', ')', '{', '}', '['和']'字符的字符串,判断该字符串是否有效

字符串是否有效:

1、开括号对应同类型的闭括号

2、按开括号顺序匹配闭括号

注意:空字符串有效

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

1:典型的堆栈问题,用字符串模拟处理,代码有注释

def isValid(s):
    """
    :type s: str
    :rtype: bool
    """
    if not s:           #判断字符串是否为空
        return True
    temp_str = ""       #存放临时开括号
    for cha in s:
        if cha == "(" or cha == "[" or cha == "{":       #如果是开括号就放入temp_str字符串中
            temp_str = temp_str + cha
        else:              
            if not temp_str:       #如果temp_str为空,返回False     
                return False
            else:                  
                temp_cha = temp_str[-1]       #取出最新压入的开括号
                temp_str = temp_str[0:-1]     #开括号字符串减一
                if temp_cha == "(" and cha == ")":      #判断开括号和闭括号是否满足要求
                    pass
                elif temp_cha == "[" and cha == "]":
                    pass
                elif temp_cha == "{" and cha == "}":
                    pass
                else:
                    return False
    if not temp_str:     #判断是否存在多余开括号
        return True
    else:
        return False

2:利用列表简化模拟压栈、出栈和判断操作

def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        temp_str = []       #存放临时开括号
        openParentheses = ["(","[","{"]
        combineParentheses = ["()","[]","{}"]
        for cha in s:
            if cha in openParentheses:       #如果是开括号就放入temp_str中
                temp_str.append(cha)
            else:
                if not temp_str:       #如果temp_str为空,返回False
                    return False
                else:
                    temp_cha = temp_str.pop() + cha     #弹出,组合
                    if temp_cha not in combineParentheses:
                        return False
        if not temp_str:     #判断是否存在多余开括号
            return True
        else:
            return False

算法题来自:https://leetcode-cn.com/problems/valid-parentheses/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/81939360