-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.go
68 lines (55 loc) · 1.28 KB
/
common.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
64
65
66
67
68
package main
import "strconv"
// Fast, preallocating buffer
func EncodeIterBuf(s string) string {
buf := make([]byte, 0, len(s)*2)
prevChar := s[0]
tempCount := 1
for i := 1; i < len(s); i++ {
if s[i] == prevChar {
tempCount++
continue
}
buf = append(buf, []byte(strconv.Itoa(tempCount))...)
buf = append(buf, prevChar)
tempCount = 1
prevChar = s[i]
}
buf = append(buf, []byte(strconv.Itoa(tempCount))...)
buf = append(buf, prevChar)
return string(buf)
}
// Slow due to string allocations
func EncodeIter(s string) string {
var resultString string
prevChar := s[0]
tempCount := 1
for i := 1; i < len(s); i++ {
if s[i] == prevChar {
tempCount++
continue
}
resultString += strconv.Itoa(tempCount) + string(prevChar)
tempCount = 1
prevChar = s[i]
}
resultString += strconv.Itoa(tempCount) + string(prevChar)
return resultString
}
// Very very slow
func EncodeRecursive(s string) string {
return encode(s, s[0], 0)
}
func encode(s string, prevChar uint8, countChar int) string {
if len(s) == 0 {
if countChar != 0 {
return strconv.Itoa(countChar) + string(prevChar)
} else {
return ""
}
}
if s[0] != prevChar {
return strconv.Itoa(countChar) + string(prevChar) + encode(s[1:], s[0], 1)
}
return encode(s[1:], prevChar, countChar+1)
}