-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_string.py
More file actions
executable file
·37 lines (26 loc) · 1.12 KB
/
decode_string.py
File metadata and controls
executable file
·37 lines (26 loc) · 1.12 KB
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
"""
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string
inside the square brackets is being repeated exactly k times.
Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for
those repeat numbers, k. For example, there won't be input like 3a or 2[4].
"""
import re
pat = r"(\d+)\[(\w+)\]"
class Solution:
def __init__(self, s: str):
self.line = s
def decode_string(self) -> str:
elements = re.findall(pat, self.line)
for el in elements:
temp = "{k}[{string}]".format(k=el[0], string=el[1])
self.line = self.line.replace(temp, int(el[0]) * el[1])
if '[' in self.line:
return self.decode_string()
else:
return self.line
if __name__ == "__main__":
inp = input("type code (for example 3[a2[c]])")
print(Solution(inp).decode_string()) # accaccacc