5/15/2020

[LeetCode] 38. Count and Say

Problem : https://leetcode.com/problems/count-and-say/

To generate the Nth term, just count and say the (N-1)th term

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        
        if n == 1:
            return "1"
        
        result = ""
        stack = []
      
        for w in self.countAndSay(n-1):
            if not stack or stack[-1] == w:
                stack.append(w)
            else:
                result += str(len(stack)) + stack[-1]
                stack = [w]

        if stack:
            result += str(len(stack)) + stack[-1]
        
        return result

No comments:

Post a Comment