LeetCode - Valid Parentheses

LeetCode - Valid Parentheses

The problem is described as following:

Given a string containing just the characters '(', ')','{', '}', '[' and']', determine if the input string is valid.

The brackets must close in the correct order, "()" and"()[]{}"are all valid but"(]"and"([)]"are not.

My Solution is as following:

class Solution:
    # @param {string} s
    # @return {boolean}
    def isValid(self, s):
        tmp = []
        for item in s:
            if item in ('(', '[', '{'):
                tmp.append(item)
            elif item == ')':
                if len(tmp) > 0 and tmp[-1] == '(':
                    tmp.pop()
                else:
                    return False
            elif item == ']':
                if len(tmp) > 0 and tmp[-1] == '[':
                    tmp.pop()
                else:
                    return False
            else:
                if len(tmp) > 0 and tmp[-1] == '{':
                    tmp.pop()
                else:
                    return False
        return len(tmp) == 0

你可能感兴趣的:(编程题目)