我的思路
两个位置
- 序列中、序列尾
由于这次的输出是下次的输入,所以在末尾加个哨兵,将末尾处理的情况一并归在循环内。
到序列中
- 遇到相同字符,计数,
- 遇到不同字符,将上一次的结果连接在字符串后,计数赋值1(因为这次的字符已经不同,所以有一个)
到序列尾
- 连接上次结果
- 加哨兵(返回之前要去掉),作为下一次输入
- 其他变量初始化
string countAndSay(int n) {
if(n == 1) return "1";
string old_s = "1", result = "";
char old_c = old_s[0], count = '0';
old_s = old_s + '0';
for(int i = 2; i <= n; ++i){
for(auto x : old_s){
if(x == '0'){
result = result + count + old_c;
old_s = result+'0';
old_c = old_s[0];
result = "";
count = '0';
}
else if(x == old_c){
++count;
}else if(x != old_c){
result = result + count + old_c;
old_c = x;
count = '1';
}
}
}
old_s.pop_back();
return old_s;
}