38. Count and Say

Medium (Trung bình) C++ Python 🔗 Xem trên LeetCode

📋 Đề Bài

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.

For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

 

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

 

Constraints:

  • 1 <= n <= 30

🧠 Thuật Toán & Kỹ Thuật

String (Chuỗi)
⏱️ Thời gian O(n²)
💾 Không gian O(1)

💻 Lời Giải

C++ 0038-count-and-say.cpp
class Solution {
public:
    string countAndSay(int n) {
        string ans = "1";
        while (--n) {
            string tmp;
            int cnt = 1, n = ans.size();
            char ptr = ans[0];
            
            for (int i = 1; i < n; ++i) {
                if (ptr == ans[i]) {
                    cnt++;
                } else {
                    tmp += to_string(cnt);
                    tmp += ptr;
                    cnt = 1, ptr = ans[i];
                }
            }
            
            tmp += to_string(cnt);
            tmp += ptr;
            
            ans = tmp;
        }
        return ans;
    }
};
Python 0038-count-and-say.py
class Solution:
    def countAndSay(self, n: int) -> str:
        ans = '1'
        
        for i in range(n - 1):
            cnt, char = 1, ans[0]
            tmp = ''
            
            for j in range(1, len(ans)):
                if char == ans[j]:
                    cnt += 1
                else:
                    tmp += str(cnt)
                    tmp += char
                    cnt, char = 1, ans[j]
            
            tmp += str(cnt)
            tmp += char
            ans = tmp
                    
        return ans