Sumnous's Blog

LEARN TO DEATH

[Leetcode] Valid Parentheses @Python

Problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    # @return a boolean
    def isValid(self, s):
        if s == '':
            return True
        left = '([{'
        right = ')]}'
        stack = []
        for i in s:
            if i == '(' or i == '[' or i == '{':
                stack.append(i)
                continue
            for j in xrange(3):
                if i == right[j]:
                    if not stack or stack[-1] != left[j]:
                        return False
                    else:
                        stack.pop()
                        continue
        return not stack
# test
s = Solution()
print s.isValid('()')