You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0400-0499/0481.Magical String/README_EN.md
+51-21
Original file line number
Diff line number
Diff line change
@@ -56,7 +56,39 @@ tags:
56
56
57
57
<!-- solution:start -->
58
58
59
-
### Solution 1
59
+
### Solution 1: Simulate the Construction Process
60
+
61
+
According to the problem, we know that each group of numbers in the string $s$ can be obtained from the digits of the string $s$ itself.
62
+
63
+
The first two groups of numbers in string $s$ are $1$ and $22$, which are obtained from the first and second digits of string $s$, respectively. Moreover, the first group of numbers contains only $1$, the second group contains only $2$, the third group contains only $1$, and so on.
64
+
65
+
Since the first two groups of numbers are known, we initialize string $s$ as $122$, and then start constructing from the third group. The third group of numbers is obtained from the third digit of string $s$ (index $i=2$), so at this point, we point the pointer $i$ to the third digit $2$ of string $s$.
66
+
67
+
```
68
+
1 2 2
69
+
^
70
+
i
71
+
```
72
+
73
+
The digit pointed by pointer $i$ is $2$, indicating that the third group of numbers will appear twice. Since the previous group of numbers is $2$, and the numbers alternate between groups, the third group of numbers is two $1$s, i.e., $11$. After construction, the pointer $i$ moves to the next position, pointing to the fourth digit $1$ of string $s$.
74
+
75
+
```
76
+
1 2 2 1 1
77
+
^
78
+
i
79
+
```
80
+
81
+
At this point, the digit pointed by pointer $i$ is $1$, indicating that the fourth group of numbers will appear once. Since the previous group of numbers is $1$, and the numbers alternate between groups, the fourth group of numbers is one $2$, i.e., $2$. After construction, the pointer $i$ moves to the next position, pointing to the fifth digit $1$ of string $s$.
82
+
83
+
```
84
+
1 2 2 1 1 2
85
+
^
86
+
i
87
+
```
88
+
89
+
Following this rule, we simulate the construction process sequentially until the length of string $s$ is greater than or equal to $n$.
90
+
91
+
The time complexity is $O(n)$, and the space complexity is $O(n)$.
60
92
61
93
<!-- tabs:start -->
62
94
@@ -70,7 +102,6 @@ class Solution:
70
102
whilelen(s) < n:
71
103
pre = s[-1]
72
104
cur =3- pre
73
-
# cur 表示这一组的数字,s[i] 表示这一组数字出现的次数
74
105
s += [cur] * s[i]
75
106
i +=1
76
107
return s[:n].count(1)
@@ -81,7 +112,7 @@ class Solution:
81
112
```java
82
113
classSolution {
83
114
publicintmagicalString(intn) {
84
-
List<Integer> s =newArrayList<>(Arrays.asList(1, 2, 2));
115
+
List<Integer> s =newArrayList<>(List.of(1, 2, 2));
0 commit comments