20. Valid Parentheses
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.
My Solution
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
i, time, len_s = 0, 0, len(s)
while time < len_s:
if s[i: i+2] == '()' or s[i: i+2] == '[]' or s[i: i+2] == '{}':
s = s[:i] + s[i+2:]
if i != 0:
i = 1
else:
time += 1
else:
i += 1
time += 1
if len(s) == 0:
return True
else:
return False
Reference (转)
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []