forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode-string.py
More file actions
executable file
·58 lines (50 loc) · 1.52 KB
/
decode-string.py
File metadata and controls
executable file
·58 lines (50 loc) · 1.52 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#recursion
#the main idea is to only calculate the mosr outer layer. (which is when stack is empty.)
#we put all the inner layer to another `decodeString()` to get its value.
#time: O(N), N is the length of the string.
#space: O(N).
class Solution(object):
def decodeString(self, s):
opt = ''
k = ''
stack = []
for i, c in enumerate(s):
if c=='[':
stack.append(i)
elif c==']':
i_start = stack.pop()
if not stack:
opt += int(k)*self.decodeString(s[i_start+1:i])
k = ''
elif c.isdigit() and not stack:
k+=c
elif not stack:
opt+=c
return opt or s
#stack
#as we iterate the string, we will dive into different level of brackets.
#we store the value of the current level in the `opt`
#and store the outer level in the stack
#when we get out of this level, we calculate the value.
#time: O(N), N is the length of the string.
#space: O(N).
class Solution(object):
def decodeString(self, s):
opt = ''
stack = []
k = ''
for c in s:
if c=='[':
stack.append(opt)
stack.append(k)
opt = ''
k = ''
elif c==']':
n = stack.pop()
pre = stack.pop()
opt = pre+int(n)*opt
elif c.isdigit():
k+=c
else:
opt+=c
return opt