-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
48 lines (38 loc) · 1019 Bytes
/
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
package main
import (
"fmt"
)
type Codec struct {
}
// Encode Encodes a list of strings to a single string.
func (codec *Codec) Encode(strs []string) string {
var out []byte
for _, str := range strs {
// important constraint is that the length of a single string
// is no more than 200 chars, we can fit it's len into a byte
out = append(out, byte(len(str)))
out = append(out, []byte(str)...)
}
return string(out)
}
// Decode Decodes a single string to a list of strings.
func (codec *Codec) Decode(in string) []string {
var out []string
for len(in) > 0 {
// first char is the length of the string
length := int(in[0])
if len(in) < length+1 { // length + string
panic("corrupted string")
}
// add a word
out = append(out, in[1:length+1])
// move to the next, skipping the length and a word
in = in[length+1:]
}
return out
}
func main() {
var codec Codec
result := codec.Decode(codec.Encode([]string{"Hello", "World"}))
fmt.Printf("Encode-Decode result: %v\n", result)
}