go: add «38. Count and Say»

URL:	https://leetcode.com/problems/count-and-say/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-04-18 12:39:33 +02:00
parent 71a5045a86
commit 591183b3ec
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

31
go/count-and-say.go Normal file
View file

@ -0,0 +1,31 @@
package main
import "fmt"
func countAndSay(n int) string {
var build func(int, string) string
build = func(idx int, result string) string {
if idx >= n {
return result
}
previous, left, count := result, 0, 0
result = ""
for right, c := range previous {
if rune(previous[left]) == c {
count++
continue
}
result += fmt.Sprint(count) + string(previous[left])
left = right
count = 1
}
result += fmt.Sprint(count) + string(previous[left])
return build(idx+1, result)
}
return build(1, "1")
}