-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path20-valid-parentheses.py
More file actions
33 lines (28 loc) · 1.13 KB
/
20-valid-parentheses.py
File metadata and controls
33 lines (28 loc) · 1.13 KB
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
31
32
33
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mappings = {
')': '(',
'}': '{',
']': '['
}
for char in s:
if char in mappings: # It's a closing bracket
top_element = stack.pop() if stack else '#'
if mappings[char] != top_element:
return False
else: # It's an opening bracket
stack.append(char)
return not stack
# Test cases
if __name__ == "__main__":
sol = Solution()
print("Testing Valid Parentheses:")
print(f"\"()\" -> {sol.isValid("()")}" + " (Expected: True)")
print(f"\"()[]{}\" -> {sol.isValid("()[]{\}")}" + " (Expected: True)")
print(f"\"(]\" -> {sol.isValid("(]")}" + " (Expected: False)")
print(f"\"{[()]}\" -> {sol.isValid("{[()]}")}" + " (Expected: True)")
print(f"\"([]){}\" -> {sol.isValid("([]){}")}" + " (Expected: True)")
print(f"\"(())\" -> {sol.isValid("(())")}" + " (Expected: True)")
print(f"\"{\" -> {sol.isValid("{")}" + " (Expected: False)")
print(f"\"]\" -> {sol.isValid("]")}" + " (Expected: False)")