题目

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.

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def isValid(self, s):
r = ""
d = {
")": "(",
"]": "[",
"}": "{",
}
for i in s:
if i in ")]}":
if r != "" and r[-1] == d[i]:
r = r[:-1]
else:
return False
else:
r += i
return True if r == "" else False