LeetCode //C - 38. Count and Say Medium Topics Companies

38. Count and Say

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 n t h n^{th} 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

From: LeetCode

Link: 38. Count and Say


Solution:

Ideas:
  1. Base Case: If n is 1, the function returns the string "1", since the first term of the sequence is always "1".
  2. Recursive Call: For n greater than 1, the function calls itself to calculate the (n-1)th term. This is because to say the nth term, you need to know the (n-1)th term first.
  3. Calculating the Length: It then calculates the length of the (n-1)th term to determine how much memory to allocate for the nth term. The allocation is generous to ensure there's enough space since the length of the sequence can grow with each term. The malloc function is used to allocate the memory, and the sprintf function is used to convert the counts and digits into a string format.
  4. Building the nth Term: The function iterates through the digits of the (n-1)th term. For each group of the same digit, it counts how many times that digit appears consecutively (count). It then writes the count and the digit itself into the result string. The sprintf function returns the number of characters written (excluding the null terminator), which is used to update the result_index to know where to write the next characters.
  5. Ending the String: Once all groups of digits have been processed, a null terminator ('\0') is added to the end of the result string to properly terminate it.
  6. Memory Management: The function then frees the memory allocated for the (n-1)th term since it is no longer needed. This is important to prevent memory leaks.
  7. Return Result: Finally, the nth term, now stored in result, is returned to the caller. The caller, in this case, the main function, is responsible for freeing this memory after it's done using it.
Code:
c 复制代码
char* countAndSay(int n) {
    if(n == 1) return strdup("1");
    
    // Recursively call countAndSay to get the previous term
    char* prev_term = countAndSay(n - 1);
    int length = strlen(prev_term);
    
    // Calculate the maximum length of the result
    // In the worst case, the length doubles (e.g., "1" -> "11")
    char* result = malloc(2 * length + 1);
    int result_index = 0;

    for(int i = 0; i < length; i++) {
        int count = 1;
        // Count the number of identical digits
        while(i + 1 < length && prev_term[i] == prev_term[i + 1]) {
            count++;
            i++;
        }
        // Append count and digit to the result string
        result_index += sprintf(result + result_index, "%d%c", count, prev_term[i]);
    }

    // Free the memory allocated for previous term
    free(prev_term);

    // Add the null terminator to the result string
    result[result_index] = '\0';
    
    return result;
}
相关推荐
cs麦子15 小时前
C语言--详解--指针--下
c语言·数据结构·算法
aitoolhub15 小时前
考研论文引用格式 AI 校验实操:工具合集 + 技术原理
c语言·人工智能·考研·aigc
flashlight_hi15 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Tisfy16 小时前
LeetCode 2536.子矩阵元素加 1:二维差分数组
算法·leetcode·矩阵
北邮刘老师16 小时前
智能家居,需要的是“主控智能体”而不是“主控节点”
人工智能·算法·机器学习·智能体·智能体互联网
oioihoii16 小时前
C++中有双向映射数据结构吗?Key和Value能否双向查找?
数据结构·c++·算法
nnn__nnn16 小时前
图像分割技术全解析:从传统算法到深度学习的视觉分割革命
深度学习·算法·计算机视觉
_OP_CHEN16 小时前
算法基础篇:(八)贪心算法之简单贪心:从直觉到逻辑的实战指南
c++·算法·贪心算法·蓝桥杯·算法竞赛·acm/icpc·简单贪心
小欣加油17 小时前
leetcode 2536 子矩阵元素加1
数据结构·c++·算法·leetcode·矩阵
橘颂TA17 小时前
【剑斩OFFER】算法的暴力美学——二维前缀和
算法·c/c++·结构与算法