Accpeted Python solution. Is this a good solution?


  • 0
    X
    class Solution:
        # @return a string
        def countAndSay(self, n):
            string = str(1)
            while n > 1:
                count = 1
                temp = ""
                for i in range(1, len(string)):
                    if string[i] != string[i-1]:
                        temp += str(count)
                        temp += string[i-1]
                        count = 1
                    else:
                        count += 1
                temp += str(count)
                temp += string[-1]
                string = temp
                n -= 1
            return string
    

    Basically, I keep a ”count“ variable to count the number of consecutive same characters. Once it encounters a character that's different from its previous one, I append the number of the previous consecutive character along with the previous character to the "temp" string and reset count to 0. After an iteration of the sequence string, if it's not the Nth sequence, continue the while loop with the updated sequence string.


  • 1
    T

    Batteries Included

    use itertools.groupby

    class Solution:
    # @return a string
    def countAndSay(self, n):
        res = '1'
        for i in range(n-1):
            stack = []
            for (k, g) in itertools.groupby(res):
                stack.append(str(len(list(g)))+k)
            res = ''.join(stack)
        return res

  • 0
    T
    This post is deleted!

Log in to reply
 

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