-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443_string_compression.go
More file actions
40 lines (36 loc) · 1018 Bytes
/
443_string_compression.go
File metadata and controls
40 lines (36 loc) · 1018 Bytes
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
package leetcode
import "strconv"
// https://leetcode.com/problems/string-compression/description/
//
// We need to store the index of where we can write next
// But the big GOTCHA is since it's a byte array, when we store the count, it must be convert to a string
// and the write index must increase accordingly
// e.g count = 10 means we need 2 space to write
// count = 100 means we need 2 space
// Need an 'if' check if the count is only 1, since we don't write the count when it's 1
// Need more 'if' checks for the final position
func compress(chars []byte) int {
nextChPos := 0
curChar := chars[0]
count := 0
for i := 0; i <= len(chars); i++ {
if i == len(chars) || curChar != chars[i] {
chars[nextChPos] = curChar
nextChPos++
if count > 1 {
countStr := strconv.Itoa(count)
for _, char := range countStr {
chars[nextChPos] = byte(char)
nextChPos++
}
count = 1
}
if i < len(chars) {
curChar = chars[i]
}
} else {
count++
}
}
return nextChPos
}