题目要求:报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, ...
1
读作 "one 1"
-> 11
11
读作 "two 1s"
-> 21
21
读作 "one 2, then one 1"
-> 1211
给定一个整数 n
, 返回 第 n
个顺序。
Notice 整数的顺序将表示为一个字符串。
输入:一个整数
输出:字符串
参考:https://cloud.tencent.com/developer/article/1142348
思路:理解题意是关键。报数是在一个n元的数列中,成员依次报数得到的结果,即n=1,输出“1”;n=2,输出根据前一步的结果得到是一个1,即"11";n=3,输出是两个1,“21”;n=4,输出是一个2一个1,“1211”;n=5,输出是一个1一个2两个1,“111221”;n=6,输出是三个1两个2一个1;n=7,输出是一个3一个1两个2两个1。
代码如下:
/**
* @param n: the nth
* @return: the nth sequence
*/
string countAndSay(int n) {
// write your code here
string res;
if (n==1) {
res.append("1");
return res;
}
else {
res = "1";
while(--n>0) {
string sb = "";
for (int i = 0; i < res.size(); i++) {
int count = 1;
while ((i+1) < res.size() && res[i] == res[i+1]) {
count++;
i++;
}
sb.append(to_string(count)+res[i]);
}
res = sb;
}
}
return res;
}