Python code using two-pointer search


  • 0
    H

    This problem is actually to scan the string, record the length of continuous duplicate characters, and update the string.

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            if n == 0:
                return ''
            s = '1'
            for k in range(n-1):
                i, j = 0, 0
                tmp = ''
                while i < len(s):
                    if j < len(s) and s[j] == s[i]: # if duplicate, increase j
                        j += 1
                    else:
                        tmp = tmp + str(j-i) + s[i] # if a new char encounterd, update tmp, 'number of duplicates'+'previous duplicated chars'
                        i = j   # move i forward
                s = tmp
                print(s)
            
            return s
    

Log in to reply
 

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