20. valid parentheses

Description

Difficulty: Easy

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

实际上就是实现一个 stack。
这里使用 dict 类型来判断左右括号是否对应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class (object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
left = {'(': 0, '[': 1, '{': 2}
right = {')': 0, ']': 1, '}': 2} # right dict
stack = [] # working stack
for i in s: # every element in s
if i in left: # if it's one of the lefts
stack.append(i) # stack push
elif i in right: # if it's one of the rights
try: # try to pop
tmp = stack.pop()
except IndexError: # if nothing to pop, return False
return False
if left[tmp] != right[i]: # if they do not match, return False
return False
if stack == []: # stack must be empty
return True
else:
return False