-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidParentheses.py
More file actions
32 lines (26 loc) · 996 Bytes
/
validParentheses.py
File metadata and controls
32 lines (26 loc) · 996 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
31
32
def isValidParentheses(s: str) -> bool:
stack = [] # Stack to keep track of opening brackets
# Mapping of closing brackets to their matching opening brackets
closetoOpenMapping = {
')': '(',
'}': '{',
']': '['
}
# Iterate through each character in the string
for char in s:
# If the character is a closing bracket
if char in closetoOpenMapping:
# Pop the top element from stack if not empty, else use a dummy value
top = stack.pop() if stack else '#'
# If the popped opening bracket does not match
if closetoOpenMapping[char] != top:
return False # Invalid parentheses
else:
# If it's an opening bracket, push it onto the stack
stack.append(char)
# If stack is empty, all brackets were matched correctly
return not stack
# Example
s = "[()}]"
result = isValidParentheses(s)
print(result)