-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathValid_Parentheses.py
More file actions
32 lines (28 loc) · 924 Bytes
/
Valid_Parentheses.py
File metadata and controls
32 lines (28 loc) · 924 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
"""
@author - Anirudh Sharma
"""
def isValid(s: str) -> bool:
# Stack for left symbols
leftSymbols = []
# Loop for each character of the string
for c in s:
# If left symbol is encountered
if c in ['(', '{', '[']:
leftSymbols.append(c)
# If right symbol is encountered
elif c == ')' and len(leftSymbols) != 0 and leftSymbols[-1] == '(':
leftSymbols.pop()
elif c == '}' and len(leftSymbols) != 0 and leftSymbols[-1] == '{':
leftSymbols.pop()
elif c == ']' and len(leftSymbols) != 0 and leftSymbols[-1] == '[':
leftSymbols.pop()
# If none of the valid symbols is encountered
else:
return False
return leftSymbols == []
if __name__ == '__main__':
print(isValid("()"))
print(isValid("()[]{}"))
print(isValid("(]"))
print(isValid("([)]"))
print(isValid("{[]}"))