-
Notifications
You must be signed in to change notification settings - Fork 0
/
394-decode-string.py
57 lines (48 loc) · 1.69 KB
/
394-decode-string.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
# [By kaka]
# class Solution:
# def decodeString(self, s: str) -> str:
# repeated = [[]]
# encoded_string = []
# ans = ""
# for c in s:
# if c == "[":
# encoded_string.append([])
# repeated.append([])
# continue
# if c == "]":
# k = int("".join(repeated[-2]))
# string = "".join(encoded_string[-1])
# ans = k * string
# repeated.pop(-2)
# encoded_string.pop()
# if len(encoded_string) < 1:
# encoded_string.append([])
# encoded_string[-1].append(ans)
# continue
# if ord(c) <= 57:
# repeated[-1].append(c)
# else:
# if len(encoded_string) < 1:
# encoded_string.append([])
# encoded_string[-1].append(c)
# return "".join(encoded_string[-1])
class Solution:
def decodeString(self, s: str) -> str:
stack = []
curNum = 0
curString = ''
for c in s:
if c == '[':
stack.append(curString)
stack.append(curNum)
curString = ''
curNum = 0
elif c == ']':
num = stack.pop()
prevString = stack.pop()
curString = prevString + num * curString
elif c.isdigit():
curNum = curNum * 10 + int(c)
else:
curString += c
return curString