forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parentheses.py
More file actions
60 lines (45 loc) · 1.2 KB
/
valid_parentheses.py
File metadata and controls
60 lines (45 loc) · 1.2 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'''
Valid Parentheses
Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string '([])[]({})', you should return true.
Given the string '([)]' or '((()', you should return false.
Input: '()[{([]{})}]'
Output: True
=========================================
Use stack. Add open brackets in the stack, remove the last bracket from the stack if there is a closing brackets.
Time Complexity: O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
from collections import deque
def is_valid(string):
closing = {
'}': '{',
']': '[',
')': '('
}
stack = deque()
for char in string:
if char in closing:
if len(stack) == 0:
return False
last = stack.pop()
if last != closing[char]:
return False
else:
stack.append(char)
return True
###########
# Testing #
###########
# Test 1
# Correct result => True
print(is_valid('()[{([]{})}]'))
# Test 2
# Correct result => False
print(is_valid('()[{([]{]})}]'))
# Test 3
# Correct result => False
print(is_valid('(]]])'))