# 38. Count and Say - CPP - Solution

• ``````// 38. Count and Say
// https://leetcode.com/problems/count-and-say/
#include <iostream>
#include <string> // required for string container and to_string() function
#include <unordered_map> // required for unordered_map container
using namespace std;
class Solution {
public:
string countAndSay(const int& n) {
string result = to_string(1);
for (size_t i = 0; i < n - 1; ++i) {
result = this->next(result);
}
return result;
}
private:
string next(const string& input) {
string result = "";
unordered_map<char, size_t> char2Num;
for (size_t i = 0; i < input.size(); ++i) {
if (!char2Num.count(input[i])) {
if (!char2Num.empty()) {
result.append(to_string(char2Num[input[i - 1]]));
result.push_back(input[i - 1]);
char2Num.erase(input[i - 1]);
}
++char2Num[input[i]];
if (i == input.size() - 1) {
result.push_back('1');
result.push_back(input[i]);
}
}
else if(char2Num.count(input[i])){
++char2Num[input[i]];
if (i == input.size() - 1) {
result.append(to_string(char2Num[input[i]]));
result.push_back(input[i]);
}
}
}
return result;
}
};
int main(int argc, const char** argv) {
Solution solution;
int n = 5;
cout << solution.countAndSay(n) << '\n';
getchar();
return 0;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.