LeetCode 38 – Python 3 (Week 05 – 08)

Solution 1

class Solution:
    def countAndSay(self, n: int) -> str:
        ans = '1' 
        for i in range(1, n):
            ans = self.getans(ans)
        return ans
    
    
    def getans(self, ans):
        i, next_ans = 0, ""
        while i < len(ans):
            count = 1
            while i < len(ans)-1 and ans[i] == ans[i+1]:
                count += 1
                i += 1
            next_ans += str(count) + ans[i]
            i += 1
        return next_ans

Time complexity is O(nk). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started