-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_missing_bracket.py
58 lines (50 loc) · 1.67 KB
/
insert_missing_bracket.py
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
""" Inserts the missing bracket into the given str """
def insert_missing_bracket(s: str) -> str:
stack = []
result = ''
for char in s:
if char in '({[':
stack.append(char)
result += char
elif char in ')}]':
if stack:
if (char == ')' and stack[-1] == '(') or \
(char == ']' and stack[-1] == '[') or \
(char == '}' and stack[-1] == '{'):
stack.pop()
result += char
else:
# Insert corresponding bracket into result
if stack[-1] == '(':
result += ')'
elif stack[-1] == '[':
result += ']'
else:
result += '}'
stack.pop()
else:
# If there is no opening bracket but closing bracket, add them to result
if char == ')':
result += ')'
elif char == ']':
result += ']'
elif char == '}':
result += '}'
else:
result += char
while stack:
# Insert corresponding bracket into result
if stack[-1] == '(':
result += ')'
elif stack[-1] == '[':
result += ']'
else:
result += '}'
stack.pop()
return result
print(insert_missing_bracket("Hello {[( world }"))
# "Hello {[( world )]}"
print(insert_missing_bracket("{[()]}"))
# "{[()]}"
print(insert_missing_bracket("{[(])}"))
# "{[()]}"