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.
Show Similar Problems
Have you met this question in a real interview?
Yes
No
need O(n) time to go through the whole array and worst case O(n) space to store the array.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for index in range(len(s)):
current_string = s[index]
if current_string == '(' or current_string == '[' or current_string == '{':
stack.append(current_string)
if current_string == ')':
if not stack or stack.pop() != '(':
return False
if current_string == ']':
if not stack or stack.pop() != '[':
return False
if current_string == '}':
if not stack or stack.pop() != '{':
return False
if stack:
return False
return True