Count and Say
数出来,确实很符合字面意思。比如 “1” 念 “一个一” 那么得出的就是 “11”; “11” 念 “两个 1” 那么得出的就是 “21”; “21” 念出来是 “一个二一个一” 那么 “1211”......
我的代码很笨拙,是这样的:
string countAndSay(int n) {
if (n < 1){
return string();
}
string result("1");
char current = '\0';
size_t count = 0;
auto saveCountAndNum = [&](string& s)
{
s.append(to_string(count));
s.push_back(current);
};
function<string(const string&)> say;
say = [&](const string& s)
{
string newStr;
current = s.front();
count = 0;
for (auto it = s.cbegin(); it != s.cend(); ++it){
if ((it + 1) == s.cend() && *it != current){
if (count != 0){
saveCountAndNum(newStr);
}
newStr.push_back('1');
newStr.push_back(*it);
}
else if ((it + 1) == s.cend() && *it == current){
++count;
saveCountAndNum(newStr);
}
else if (*it != current){
saveCountAndNum(newStr);
current = *it;
count = 1;
}
else{
++count;
}
}
return newStr;
};
for (int i = 1; i != n; ++i){
result = say(result);
}
return result;
}
浙公网安备 33010602011771号