Stack
We match and pop matching pairs using a stack. If s is valid, in the end, the stack must be empty.
Time: , space: same.
class Solution:
def isValid(self, s: str) -> bool:
pair_of = defaultdict(str, {")": "(", "}": "{", "]": "["})
stack = []
for c in s:
if stack and stack[-1] == pair_of[c]:
stack.pop()
else:
stack.append(c)
return not stack
Two pointers
Like this problem, if we are allowed to modify the string s in-place, we need constant extra space.
Time: , space:
.
class Solution:
def is_matching_pair(self, i, j, s) -> bool:
if i < 0:
return False
return (
(s[i] == "(" and s[j] == ")")
or (s[i] == "{" and s[j] == "}")
or (s[i] == "[" and s[j] == "]")
)
def isValid(self, s: str) -> bool:
s = list(s)
i = -1
for j in range(len(s)):
if self.is_matching_pair(i, j, s):
i -= 1
else:
i += 1
s[i] = s[j]
return i == -1
Leave a comment