-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasystack_20_validParentheses.py
More file actions
40 lines (29 loc) · 992 Bytes
/
easystack_20_validParentheses.py
File metadata and controls
40 lines (29 loc) · 992 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
33
34
35
36
37
38
"""
https://leetcode.com/problems/valid-parentheses/
https://www.youtube.com/watch?v=WTzjTskDFMg&list=PLot-Xpze53lfQmTEztbgdp8ALEoydvnRQ&index=12
leetcode 20
easy
stack or python list
input :
output:
Logic :
Time Complexity:
"""
def isValid(s):
Map = {")": "(", "]": "[", "}": "{"} #hashmap for all bracket pairs
stack = []
for c in s: #loop on input string
# if c is closing parentheses (all keys of map)
if c in Map:
# and stack is not empty since we cant add closing to empty stack
# and value at top of stack is matching opening
if stack and stack[-1] == Map[c]:
stack.pop()
else:
return False
else : #else if it was an opening parentheses then just add to stack
stack.append(c)
return True if not stack else False
print(isValid("()"))
print(isValid("()[]{}"))
print(isValid("(]"))