Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Input: "()" Output: true
Input: "()[]{}" Output: true
Input: "(]" Output: false
Input: "([)]" Output: false
Input: "{[]}" Output: true
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
brackets = {')': '(', '}': '{', ']': '['}
stack = []
for c in s:
if c in brackets and stack and stack[-1] == brackets[c]:
stack.pop()
else:
stack.append(c)
return not stack
class Solution:
def isValid(self, s: str) -> bool:
while s.count("()") or s.count("[]") or s.count("{}"):
s = s.replace("()", "")
s = s.replace("[]", "")
s = s.replace("{}", "")
return not s