The “Count and Say” sequence is a sequence of digit strings defined by the following recursive formula:
countAndSay(1)
is "1"
."1"
is "11"
, because we have one 1
(“one 1” hence “11”).Given an integer n
, generate the n
-th term of the “Count and Say” sequence.
n
we need to consider?
n = 1
, which is “1”.1
to n
.
n = 0
which should return an empty string, although the problem statement starts counting from 1
.Here is the implementation to solve the problem.
#include <iostream>
#include <string>
class Solution {
public:
std::string countAndSay(int n) {
if (n == 1) return "1";
std::string result = "1";
for (int i = 2; i <= n; ++i) {
std::string current = "";
int len = result.size();
for (int j = 0; j < len; ++j) {
int count = 1;
while (j + 1 < len && result[j] == result[j + 1]) {
++count;
++j;
}
current += std::to_string(count) + result[j];
}
result = current;
}
return result;
}
};
// Example usage:
// int main() {
// Solution sol;
// int n = 4;
// std::cout << sol.countAndSay(n) << std::endl; // Output should be "1211"
// return 0;
// }
n
is the given input and m
is the maximum length of any string in the sequence up to n
. In the worst case, the length of the string could approximately double at each step (though it’s typically less than that in practice).m
is the length of the string at each step since we only build the next string based on the current one.This approach ensures that the sequence is generated efficiently and handles varying sizes of n
smoothly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?