481. Magical String

Description

image-20210820215930110

Solution

Use a pointer to record current occurrence of next segment of s. The new added segment’s consecutive number should be different from back of s.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def magicalString(self, n: int) -> int:
if n <= 3:
return 1

s = "122"
freq,size,res = 2, 3, 1 #freq postion pointer
while size < n:
f = int(s[freq])
c = 1 if s[len(s)-1] is "2" else 2
s += str(c) * f
if size + f >= n:
if c == 1:
res += n - size
else:
if c == 1:
res += f
size += f
freq += 1
return res

image-20210820220356366