Count and Say

Problem Id: 38 Difficulty: Medium Tag: String


Intuition

Just solve it recurisivly.

Solution


class Solution:
    def countAndSay(self, n: int) -> str:
        if n == 1:
            return '1'

        s = self.countAndSay(n - 1)
        prev = None
        count = 0
        res = []
        for c in s + '\0':
            if c != prev:
                if prev is not None:
                    res.append(str(count))
                    res.append(str(prev))
                prev = c
                count = 1
            else:
                count += 1
        return ''.join(res)