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
We can use two pointers to count the consecutive occurrences of each character. Suppose the current character $c$ appears consecutively $k$ times, then we divide $k$ into several $x$, each $x$ is at most $9$, then we concatenate $x$ and $c$, and append each $x$ and $c$ to the result.
82
+
83
+
Finally, return the result.
84
+
85
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the
80
86
81
87
<!-- tabs:start -->
82
88
83
89
#### Python3
84
90
85
91
```python
86
-
92
+
classSolution:
93
+
defcompressedString(self, word: str) -> str:
94
+
g = groupby(word)
95
+
ans = []
96
+
for c, v in g:
97
+
k =len(list(v))
98
+
while k:
99
+
x =min(9, k)
100
+
ans.append(str(x) + c)
101
+
k -= x
102
+
return"".join(ans)
87
103
```
88
104
89
105
#### Java
90
106
91
107
```java
92
-
108
+
classSolution {
109
+
publicStringcompressedString(Stringword) {
110
+
StringBuilder ans =newStringBuilder();
111
+
int n = word.length();
112
+
for (int i =0; i < n;) {
113
+
int j = i +1;
114
+
while (j < n && word.charAt(j) == word.charAt(i)) {
0 commit comments