-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
74 lines (70 loc) · 1.39 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"strconv"
)
//Runtime: 4 ms, faster than 58.25% of Go online submissions for Count and Say.
//func countAndSay(n int) string {
// var str = "1"
// var getStr = func(str string) (next string) {
// for i := 0; i < len(str); i++ {
// if i == len(str)-1 {
// next += "1" + string(str[i])
// } else {
// var n int = 0
// var v = str[i]
// for i < len(str) {
// if str[i] == v {
// n++
// i++
// } else {
// next += strconv.Itoa(n) + string(v)
// n = 0
// i--
// break
// }
// }
// if n != 0 {
// next += strconv.Itoa(n) + string(v)
// }
// }
// }
// return next
// }
// for i := 1; i < n; i++ {
// str = getStr(str)
// }
// return str
//}
//Runtime: 0 ms, faster than 100.00% of Go online submissions for Count and Say.
func countAndSay(n int) string {
if n == 1 {
return "1"
}
lastString := "1"
for i := 2; i <= n; i++ {
var results []byte
lastByte := lastString[0]
num := 1
for j := range lastString {
if j == 0 {
continue
}
if lastString[j] == lastByte {
num++
} else {
results = append(results, byte(num+48))
results = append(results, lastByte)
lastByte = lastString[j]
num = 1
}
}
results = append(results, byte(num+48))
results = append(results, lastByte)
lastString = string(results)
}
return lastString
}
func main() {
fmt.Println(countAndSay(6))
}