Skip to content

38. Count and Say

https://leetcode.com/problems/count-and-say/

js
/**
 * @param {number} n
 * @return {string}
 */
var countAndSay = function(n) {
  if (n === 1) {
    return '1'
  }
  return sayNum(countAndSay(n - 1))
}

function sayNum(numStr) {
  var nums = numStr.split('')
  var result = []
  var num = null
  var count = 0

  nums.forEach(x => {
    if (x === num) {
      count++
    } else {
      if (count) {
        result.push(count, num)
      }
      num = x
      count = 1
    }
  })
  result.push(count, num)

  return result.join('')
}
py
class Solution(object):

    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        return '1' if n == 1 else self.sayNum(self.countAndSay(n - 1))

    def sayNum(self, num):
        cur, count = None, 0
        result = []
        for n in num:
            if cur == n:
                count += 1
            else:
                if count:
                    result += str(count), cur
                cur, count = n, 1

        result += str(count), cur
        return ''.join(result)