Python solution, beats ~95%


  • 0
    J

    This question's wording was very misleading! But the top posts here made that clear. Here's my solution:

    in the main function, take "1" as starting input and transform the input as many times as n requires.

    In the transform function, take the string and keep count of each digit's repetitions. When a new digit is found, write the old digit and its count to the result string. Finally, return the result string and repeat transformation if necessary.

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            input = "1"
            for i in xrange(0,n-1):
                input = self.transform(input)
            return input    
        
            
        def transform(self,input):   
            last = input[0]
            last_count=1
            res = ""
            for i in xrange(1,len(input)):
                letter = input[i]
                if last==letter:
                    last_count+=1
                else:
                    res+=str(last_count)+last
                    last_count=1
                last = letter
            res+=str(last_count)+str(last)        
            return res 
    

Log in to reply
 

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