题目二十六:
报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, ...
1
读作 "one 1"
-> 11
.
11
读作 "two 1s"
-> 21
.
21
读作 "one 2, then one 1"
-> 1211
.
给定一个整数 n
, 返回 第 n
个顺序。
注意事项
整数的顺序将表示为一个字符串。
样例
代码:
给定 n = 5
, 返回 "111221"
.
class Solution {
public:
/**
* @param n: the nth
* @return: the nth sequence
*/
string countAndSay(int n) {
// write your code here
string a;
string b;
char c;
string d;
stringstream f;
a="1";
b="";
int i,j,num;
for(i=1;i<n;i++)
{
c=a[0];
num=0;
j=0;
while(j<a.length())
{
while(a[j]==c)
{
num++;
j++;
}//a[j]!=c时退出循环
f.str("");
f<<num;
d=f.str();
b=b+d+c;
c=a[j];
num=0;
}
a=b;
b="";
}
return a;
}
};
思路:下一个字符串是上一个字符串中相邻相同字符的个数+该字符的集合,例:1211 :1个1(11)1个2(12)2个1(21)下一个:111221。所以只要依次计算
相邻相同字符的个数按着上述规律不断地累加在一个新字符串上就能得到下一个字符串。要注意每获得一个新的字符串都要对各个变量进行重新赋值。详见代码。
在计数器num转换成string时要注意字符串流的清除(f.str(""));否则会一直累加之前的num转换的字符串。