leetcode/src/s0038_count_and_say.cpp

22 lines
438 B
C++
Raw Normal View History

2022-11-22 10:06:14 +00:00
#include "s0038_count_and_say.hpp"
2022-11-30 10:20:36 +00:00
string S0038::countAndSay(int n) {
2022-11-22 10:06:14 +00:00
if (n == 1) {
return "1";
} else if (n <= 0) {
return "";
}
string prev = countAndSay(n - 1);
string result{""};
int len = prev.length();
int pos{0}, start{0};
while (pos < len) {
while (pos < len && prev[pos] == prev[start]) {
pos++;
}
result += to_string(pos - start) + prev[start];
start = pos;
}
return result;
}