0
点赞
收藏
分享

微信扫一扫

38. Count and Say

沈芏 2022-12-01 阅读 141


he count-and-say sequence is the sequence of integers beginning as follows:

​1, 11, 21, 1211, 111221, ...​​​​1​​ is read off as ​​"one 1"​​ or ​​11​​.

​11​​ is read off as ​​"two 1s"​​ or ​​21​​.

​21​​ is read off as ​​"one 2​​, then ​​one 1"​​ or ​​1211​​.

n, generate the nth

Note: The sequence of integers will be represented as a string.

直接模拟

class Solution {
public:
string countAndSay(int n) {
string str;
for (int i = 1; i <= n; i++){
if (i == 1){
str = "1";
}
else{
string tmp;
int len = str.size();
int j = 0;
int ini = 0;
while (j <= len){
if (j<len&&str[j] == str[ini]){
j++;
}
else{
tmp.append(to_string(j-ini));
tmp += str[ini];//如果用to_string返回的是ASCII码
ini = j;
j++;
}
}
str = tmp;
}
}
return str;
}
};



举报

相关推荐

0 条评论