Given a string s
containing just the characters '('
, ')'
, '{'
, }'
, '['
, and ']'
, determine if the input string is valid.
An input string is valid if:
'('
, ')'
, '{', '}'
, '['
, and ']'
.True
if the string is valid, otherwise return False
.'('
, '{'
, '['
), push it onto the stack.')'
, '}'
, ']'
), check if the stack is not empty and whether the top of the stack is the corresponding opening bracket. If so, pop the stack. If not, the string is invalid.def isValid(s: str) -> bool:
# Dictionary to match opening and corresponding closing brackets
matching_bracket = {')': '(', '}': '{', ']': '['}
# Stack to keep track of opening brackets
stack = []
for char in s:
if char in matching_bracket.values(): # If it is one of the opening brackets
stack.append(char)
elif char in matching_bracket.keys(): # If it is one of the closing brackets
if stack == [] or stack.pop() != matching_bracket[char]:
return False
# Check whether the stack is empty (all brackets matched and closed)
return stack == []
# Example usage
print(isValid("()")) # Output: True
print(isValid("()[]{}")) # Output: True
print(isValid("(]")) # Output: False
print(isValid("([)]")) # Output: False
print(isValid("{[]}")) # Output: True
O(n)
where n
is the length of the string s
. Each character is processed once, either pushed onto the stack or matched and popped.O(n)
in the worst case, if all the characters in the string are opening brackets, they will all be pushed onto the stack.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?