February 23, 2023
Problem Source: Leetcode
Given a string s containing just the characters (
, )
, {
, }
, [
and ]
, determine if the input string is valid.
An input string is valid if:
Constraints:
1 <= s.length <= 104
s
consists of parentheses only ()[]{}
.def test(fn):
s = "()"
expected = True
assert fn(s) == expected
s = "()[]{}"
expected = True
assert fn(s) == expected
s= "(]"
expected = False
assert fn(s) == expected
O(n)
O(n)
def isValid(s: str) -> bool:
enclosures = {')':'(','}':'{',']':'['}
stack = []
for c in s:
# If it's an closing bracket
if c in enclosures:
# Validate stack exists and bracket order is correct
if stack and stack[-1] == enclosures[c]:
stack.pop()
else:
return False
else:
# If it's an opening bracket
stack.append(c)
# If stack isn't empty then an enclosure isn't closed
return not stack
test(isValid)