LeetCode 038 Count and Say

LeetCode 038 Count and Say Problem

Download Code
class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 1:
            return '1'
        x = '1'
        while n > 1:
            # each round, read itself
            x = self.count(x)
            n -= 1
        return x

    def count(self, x):
        m = list(x)
        res = []
        m.append(None)
        i , j = 0 , 0
        while i < len(m) - 1:
            j += 1
            if m[j] != m[i]:
                # note j - i is the count of m[i]
                res += [j - i, m[i]]
                i = j
        return ''.join(str(s) for s in res)
Download Count and Say.py

List of all Count and Say problems

Leetcode 038 Count and Say problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.