-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-and-say.go
54 lines (47 loc) · 988 Bytes
/
count-and-say.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
package main
import (
"bytes"
"fmt"
"strconv"
)
var memo = map[int]string{
1: "1",
}
func countAndSay(n int) string {
if res, ok := memo[n]; ok {
return res
}
var res bytes.Buffer
count := 0
inp := countAndSay(n - 1)
for i := 0; i < len(inp); i++ {
count++
if i == len(inp)-1 || inp[i] != inp[i+1] {
res.WriteString(strconv.Itoa(count))
res.WriteByte(inp[i])
// res += strconv.Itoa(count) + string(inp[i])
count = 0
}
}
memo[n] = res.String()
return res.String()
}
func main() {
println("Started...")
test := 1
fmt.Printf("Testing: %v\n", test)
result := countAndSay(test)
fmt.Printf("Yields : %v\n", result)
test = 2
fmt.Printf("Testing: %v\n", test)
result = countAndSay(test)
fmt.Printf("Yields : %v\n", result)
test = 10
fmt.Printf("Testing: %v\n", test)
result = countAndSay(test)
fmt.Printf("Yields : %v\n", result)
test = 30
fmt.Printf("Testing: %v\n", test)
result = countAndSay(test)
fmt.Printf("Yields : %v\n", result)
}