Solve 38. Count and Say
This commit is contained in:
parent
2726e1ec76
commit
66fbabec99
|
@ -0,0 +1,104 @@
|
|||
#+title: 38. Count And Say
|
||||
#+author: Samuel Ortion
|
||||
#+date: <2025-03-01 Sat>
|
||||
|
||||
* Subject
|
||||
|
||||
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
|
||||
|
||||
countAndSay(1) = "1"
|
||||
countAndSay(n) is the run-length encoding of countAndSay(n - 1).
|
||||
|
||||
Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "3322251" we replace "33" with "23", replace "222" with "32", replace "5" with "15" and replace "1" with "11". Thus the compressed string becomes "23321511".
|
||||
|
||||
Given a positive integer n, return the nth element of the count-and-say sequence.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: n = 4
|
||||
|
||||
Output: "1211"
|
||||
|
||||
Explanation:
|
||||
|
||||
countAndSay(1) = "1"
|
||||
countAndSay(2) = RLE of "1" = "11"
|
||||
countAndSay(3) = RLE of "11" = "21"
|
||||
countAndSay(4) = RLE of "21" = "1211"
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: n = 1
|
||||
|
||||
Output: "1"
|
||||
|
||||
Explanation:
|
||||
|
||||
This is the base case.
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
1 <= n <= 30
|
||||
|
||||
|
||||
Follow up: Could you solve it iteratively?
|
||||
|
||||
|
||||
* Solution
|
||||
|
||||
#+begin_src C
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
char *runLengthEncoding(char *message) {
|
||||
// Realloc to two times the message size,
|
||||
// as in the worst case scenario,
|
||||
// the encoding occupies twice as much memory as the message
|
||||
size_t len = strlen(message);
|
||||
char *encoding = malloc((2 * len + 1) * sizeof(char));
|
||||
int cursor = 0;
|
||||
int i = 0;
|
||||
|
||||
while (i < len) {
|
||||
char letter = message[i];
|
||||
int count = 0;
|
||||
while (i < len && message[i] == letter) {
|
||||
count++;
|
||||
i++;
|
||||
}
|
||||
encoding[cursor] = count + '0';
|
||||
encoding[cursor+1] = letter;
|
||||
cursor += 2;
|
||||
}
|
||||
encoding[cursor] = '\0';
|
||||
return encoding;
|
||||
}
|
||||
|
||||
char* countAndSay(int n) {
|
||||
char *term = malloc(2 * sizeof(char));
|
||||
term[0] = '1';
|
||||
term[1] = '\0';
|
||||
for (int i=1; i < n; i++) {
|
||||
char *next = runLengthEncoding(term);
|
||||
free(term);
|
||||
term = next;
|
||||
}
|
||||
return term;
|
||||
}
|
||||
|
||||
int main() {
|
||||
printf("%s\n", countAndSay(2));
|
||||
printf("%s\n", countAndSay(3));
|
||||
printf("%s\n", countAndSay(4));
|
||||
}
|
||||
#+end_src
|
||||
|
||||
#+RESULTS:
|
||||
| 11 |
|
||||
| 21 |
|
||||
| 1211 |
|
Loading…
Reference in New Issue