Decode String

Decode String

stack version - 32ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
stack.append(["", 1])
num = ""
for ch in s:
if ch.isdigit():
num += ch
elif ch == '[':
stack.append(["", int(num)])
num = ""
elif ch == ']':
st, k = stack.pop()
stack[-1][0] += st*k
else:
stack[-1][0] += ch
return stack[0][0]

test code

1
2
In [109]: s = Solution(); t = s.decodeString("3[a]2[bc]"); print(t)
aaabcbc

leet code