-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
63 lines (59 loc) · 1.01 KB
/
main.go
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
54
55
56
57
58
59
60
61
62
63
package main
import (
"strconv"
)
// brute force
// time complexity: O(n)
// space complexity: O(1)
func compress(chars []byte) int {
count, pnt := 1, 1
for i := 1; i < len(chars); i++ {
if chars[i] == chars[i-1] {
count++
} else {
if count != 1 {
num := strconv.Itoa(count)
for l := 0; l < len(num); l++ {
chars[pnt] = num[l]
pnt++
}
}
chars[pnt] = chars[i]
pnt++
count = 1
}
if i == len(chars)-1 {
if count != 1 {
num := strconv.Itoa(count)
for l := 0; l < len(num); l++ {
chars[pnt] = num[l]
pnt++
}
}
}
}
return pnt
}
// optimize compress
// time complexity: O(n)
// space complexity: O(1)
func compress2(chars []byte) int {
var ans int
for i := 0; i <= len(chars)-1; i++ {
groupLen := 1
for i < len(chars)-1 && chars[i] == chars[i+1] {
groupLen++
i++
}
chars[ans] = chars[i]
ans++
if groupLen > 1 {
str := strconv.Itoa(groupLen)
for l := 0; l < len(str); l++ {
chars[ans] = str[l]
ans++
}
}
}
return ans
}