-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20 valid parentheses.py
More file actions
30 lines (26 loc) · 998 Bytes
/
Copy path20 valid parentheses.py
File metadata and controls
30 lines (26 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
"""Given a string s 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.
"""
class Solution:
def isValid(self, s: str) -> bool:
stack = []
opening = set('([{')
matching = {')': '(', ']': '[', '}': '{'}
for c in s:
if c in opening: stack.append(c)
elif not stack or stack.pop() != matching[c]: return False
return not stack
testcases = [
{'input': (r"()",), 'result': True},
{'input': (r"()[]{}",), 'result': True},
{'input': (r"(]",), 'result': False},
{'input': (r"([)]",), 'result': False},
{'input': (r"{[]}",), 'result': True},
{'input': (r"}",), 'result': False},
{'input': (r"[",), 'result': False},
]
from leettest import test
test(Solution().isValid, testcases)