-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0394-decode-string.py
More file actions
32 lines (29 loc) · 835 Bytes
/
0394-decode-string.py
File metadata and controls
32 lines (29 loc) · 835 Bytes
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
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def decodeString(self, s: str) -> str:
current = ""
countStack = []
stringStack = []
k = 0
for c in s:
if c.isdigit():
k = k * 10 + int(c)
elif c == '[':
countStack.append(k)
stringStack.append(current)
k = 0
current = ""
elif c == ']':
prevString = stringStack.pop()
prevNum = countStack.pop()
current = prevString + current * prevNum
else:
current += c
return current
s = "3[a]2[bc]"
print(Solution().decodeString(s))
s = "3[a2[c]]"
print(Solution().decodeString(s))
s = "2[abc]3[cd]ef"
print(Solution().decodeString(s))