13.go 613 B

123456789101112131415161718192021222324252627282930
  1. package main
  2. import (
  3. "strings"
  4. "fmt"
  5. "math"
  6. )
  7. // iterator of countAndSay function
  8. func casIter(last string, n int) string {
  9. if n == 1 { return last }
  10. next := make([]rune, 0)
  11. curr := last[0]
  12. cnt := 1
  13. for i := 1; i < len(last); i++ {
  14. if curr != last[i] {
  15. next = append(next, rune(cnt + '0'), rune(curr))
  16. curr = last[i]
  17. cnt = 1
  18. } else {
  19. cnt++
  20. }
  21. }
  22. next = append(next, rune(cnt + '0'), rune(curr))
  23. return casIter(string(next), n - 1)
  24. }
  25. func countAndSay(n int) string {
  26. return casIter("1", n)
  27. }