The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
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.
Input: n = 1
Output: “1”
Explanation: This is the base case.
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”
From: LeetCode
Link: 38. Count and Say
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;
}