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:
parent
71a5045a86
commit
591183b3ec
1 changed files with 31 additions and 0 deletions
31
go/count-and-say.go
Normal file
31
go/count-and-say.go
Normal 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")
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue