38.go 482 B

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