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:
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;
}

相关推荐

  1. 38 事件

    2024-04-26 11:46:04       18 阅读
  2. 代码随想录 day37|day38|day39

    2024-04-26 11:46:04       10 阅读
  3. 38 调优kafka

    2024-04-26 11:46:04       42 阅读
  4. 38.外观数列

    2024-04-26 11:46:04       40 阅读
  5. LeetCode 38. 外观数列

    2024-04-26 11:46:04       35 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-26 11:46:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-26 11:46:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-26 11:46:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-26 11:46:04       20 阅读

热门阅读

  1. 重新理解React-hook

    2024-04-26 11:46:04       12 阅读
  2. npm config set registry切换npm镜像源

    2024-04-26 11:46:04       13 阅读
  3. Spring Boot 启动流程

    2024-04-26 11:46:04       10 阅读
  4. 数仓开发LAG 和 LEAD 函数详细解析和用例

    2024-04-26 11:46:04       13 阅读
  5. Git 的基本概念和使用方式

    2024-04-26 11:46:04       13 阅读
  6. GO语言核心30讲 笔记

    2024-04-26 11:46:04       13 阅读
  7. 反编译jar包

    2024-04-26 11:46:04       10 阅读
  8. DVWA下半部分

    2024-04-26 11:46:04       13 阅读
  9. Centos7 tcpdump -w 时遇到 Permission denied

    2024-04-26 11:46:04       11 阅读
  10. mac下安装python并编写脚本实现s3上传功能

    2024-04-26 11:46:04       14 阅读
  11. nvm安装及使用(mac)

    2024-04-26 11:46:04       12 阅读
  12. 最小路径和

    2024-04-26 11:46:04       17 阅读
  13. Ajax 笔记 01

    2024-04-26 11:46:04       11 阅读
  14. 华纳云:如何使用Docker进行有效的日志管理?

    2024-04-26 11:46:04       14 阅读
  15. 【MySQL】排序和分页

    2024-04-26 11:46:04       16 阅读
  16. STM32中UART通信的完整C语言代码范例

    2024-04-26 11:46:04       13 阅读