LC 0038 [M] Count and Say - ALawliet/algorithms GitHub Wiki

Idea here is keep track of the first letter in the sequence and count consecutive occurences. Once you encounter a new letter you add the previous count and letter to the chain. Repeat n-1 times (since we seeded the initial '1' case). We always update temp after the inner loop since we will never have already added the last sequence.

class Solution:
    def countAndSay(self, n):
        s = '1'
        for _ in range(n-1):
            cur = s[0]
            group = ''
            count = 0
            for x in s:
                if x == cur: # combo
                    count += 1
                else: # next char
                    group += str(count) + cur
                    cur = x
                    count = 1
            group += str(count) + cur
            s = group
        return s
def countAndSay(self, n):
    res = '1'
    for _ in range(n-1):
        prev = res
        res = ''
        j = 0
        while j < len(prev):
            cur = prev[j]
            count = 1
            j += 1
            while j < len(prev) and prev[j] == cur:
                count += 1
                j += 1
            res += str(count) + cur
    return res