-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdecode_str.py
43 lines (42 loc) · 1.13 KB
/
decode_str.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
'''
Input: 'ab[cd]{2}'
Output: 'abcdcd'
Input: 'def[ab[cd]{2}]{3}ghi'
Output: 'defabcdcdabcdcdabcdcdghi'
'''
def decode(sudo):
if sudo == None:
return None
if sudo == "":
return ""
lsudo = list(sudo)
foo = [] #stack
res = ''
for i in range(len(lsudo)):
if lsudo[i] == '[':
partial = ""
i += 1
while i < len(lsudo) and lsudo[i] != ']' and lsudo[i] != '[':
partial += lsudo[i]
i += 1
foo.append(partial) #lsudo[i] == ']' or lsudo[i] == '['
i -= 1
elif lsudo[i] == '{':
i += 1
if len(foo) == 0:
return -1
num = ''
while i < len(lsudo) and lsudo[i] != '}':
num += lsudo[i]
top = foo.pop()
re = top*int(num)
res.append(re)
if foo != []:
popped = foo.pop()
foo.append(popped + re)
else:
foo.append(re)
elif lsudo[i] >= 'a' and lsudo[i] <= 'z':
res += lsudo[i]
return res
print(decode(str(input())))