forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneverlish.go
More file actions
48 lines (43 loc) · 910 Bytes
/
neverlish.go
File metadata and controls
48 lines (43 loc) · 910 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
41
42
43
44
45
46
47
48
// 시간복잡도: O(n)
// 공간복잡도: O(n)
package main
import (
"bytes"
"fmt"
"strconv"
"testing"
)
func TestEncodeAndDecode(t *testing.T) {
strs := []string{"abc", "def", "ghi"}
encoded := encode(strs)
decoded := decode(encoded)
if len(strs) != len(decoded) {
t.Errorf("Expected %v but got %v", strs, decoded)
}
for i := 0; i < len(strs); i++ {
if strs[i] != decoded[i] {
t.Errorf("Expected %v but got %v", strs, decoded)
}
}
}
func encode(strs []string) string {
var buffer bytes.Buffer
for _, str := range strs {
buffer.WriteString(fmt.Sprintf("%d~", len(str)))
buffer.WriteString(str)
}
return buffer.String()
}
func decode(str string) []string {
var result []string
for i := 0; i < len(str); {
j := i
for str[j] != '~' {
j++
}
length, _ := strconv.Atoi(str[i:j])
result = append(result, str[j+1:j+1+length])
i = j + 1 + length
}
return result
}