題目:
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.
題解:
【字符串處理】
用一個List當作堆棧,遇到左括號壓棧,遇到右括號彈棧比較。
最後check一下棧是否爲空即可。
Code:
class Solution:
# @return a boolean
def isValid(self, s):
p = []
l = ['(','[','{']
r = [')',']','}']
for c in s:
if c in l:
p.append(c)
elif c in r:
if p == []:
return False
if p.pop() != l[r.index(c)]:
return False
if p == []:
return True
else:
return False