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
| func compress(chars []byte) int {
n := len(chars)
if n <= 1 {
return n
}
index := 0
count := 1
for i := 1; i < n; i++ {
if chars[i] == chars[i-1] {
count++
} else {
chars[index] = chars[i-1]
index++
if count > 1 {
countStr := strconv.Itoa(count)
for j := 0; j < len(countStr); j++ {
chars[index] = countStr[j]
index++
}
}
count = 1
}
}
chars[index] = chars[n-1]
index++
if count > 1 {
countStr := strconv.Itoa(count)
for j := 0; j < len(countStr); j++ {
chars[index] = countStr[j]
index++
}
}
return index
}
|