Somewhat short Python Solution

  • 0
    class Solution:
        # @return a string
        # memoization
        ret = {1:"1"}
        def countAndSay(self, n):
            if n==1:
                return self.ret[1]
            elif n in self.ret:
                return self.ret[n]
            else: # ret[n] doesn't exist
                self.ret[n] = self.proceed(self.countAndSay(n-1),1)
                return self.ret[n]
        def proceed(self,s,index): # return the next string based on string s
            if len(s)==1:
                return str(index)+s[0]
            elif s[0]==s[1]:
                return self.proceed(s[1:],index+1)
            else: # s[0]!=s[1]
                return str(index)+s[0]+self.proceed(s[1:],1)

Log in to reply

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