Python, LintCode, 423. 有效的括号序列

class Solution:
    """
    @param s: A string
    @return: whether the string is a valid parentheses
    """
    def isValidParentheses(self, s):
        # write your code here
        N = len(s)
        if N == 0:
            return True
        if N%2 == 1:
            return False
        tmp = []    
        for i in range(N):
            if s[i] == "(":
                tmp.append(1)
            if s[i] == "{":
                tmp.append(2)
            if s[i] == "[":
                tmp.append(3)
            if s[i] == ")":
                try:
                    if tmp.pop() != 1:
                        return False
                except:
                    return False
            if s[i] == "}":
                try:
                    if tmp.pop() != 2:
                        return False
                except:
                    return False
            if s[i] == "]":
                try:
                    if tmp.pop() != 3:
                        return False
                except:
                    return False
        if len(tmp) != 0:
            return False
        return True

猜你喜欢

转载自blog.csdn.net/u010342040/article/details/80258354