Python, iterate and recursive, O(n*m)


  • 0
    0

    Recursive

    class Solution(object):
        def countAndSay(self, n):
            return ''.join(self.helper(['1'], n-1))
        
        def helper(self, A, n):
            if not n:
                return A
            c = 0
            B = []
            for i in range(len(A)):
                c += 1
                if i == len(A)-1 or A[i]!=A[i+1]:
                    B += [str(c), A[i]]
                    c = 0
            return self.helper(B, n-1)
    

    Iterative

    class Solution(object):
        def countAndSay(self, n):
            A = ['1']
            count = 0
            for _ in range(1,n):
                temp = []
                for i in range(len(A)):
                    count += 1
                    if i==len(A)-1 or A[i] != A[i+1]:
                        temp.extend([str(count), A[i]])
                        count = 0
                
                A = temp
                count = 0
                
            return ''.join(A)
                        
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.