Skip to content

Commit

Permalink
feature: valid parentheses revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Dec 4, 2023
1 parent e652d20 commit 1d4d9b9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
13 changes: 6 additions & 7 deletions stack/ValidParentheses.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# O(n) time || O(n) space
def is_valid(self, s: str) -> bool:
close_to_open, stack = {")": "(", "]": "[", "}": "{"}, []
for c in s:
if c not in close_to_open:
stack.append(c)
elif stack:
if stack.pop() != close_to_open[c]:
brackets = {')': '(', ']': '[', '}': '{'}
stack = []
for br in s:
if br in brackets:
if not stack or stack.pop() != brackets[br]:
return False
else:
return False
stack.append(br)

return not stack
6 changes: 6 additions & 0 deletions stack/test/test_is_valid.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ def test_is_valid_1(self):
def test_is_valid_2(self):
self.assertEqual(False, is_valid(self, "(]"))

def test_is_valid_3(self):
self.assertEqual(True, is_valid(self, "{[]}"))

def test_is_valid_4(self):
self.assertEqual(False, is_valid(self, "]"))


if __name__ == '__main__':
unittest.main()

0 comments on commit 1d4d9b9

Please sign in to comment.