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.
Solution
(Valid-Parentheses.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
stack = []
for c in s:
if c in '({[':
stack.append(c)
else:
if len(stack) == 0:
return False
top = stack.pop()
if top == '(' and c != ')':
return False
if top == '{' and c != '}':
return False
if top == '[' and c != ']':
return False
if len(stack) == 0:
return True
else:
return False
|