您的位置:首页 > 其它

leetcode38---Count and Say

2016-01-15 09:59 483 查看
问题描述:

The 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.


Given an integer n, generate the nth sequence.

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

也就是说:

输入n,那么我就打出第n行的字符串。

规律如下:

n = 1时,打印一个1。
n = 2时,看n=1那一行,念:1个1,所以打印:11。
n = 3时,看n=2那一行,念:2个1,所以打印:21。
n = 4时,看n=3那一行,念:一个2一个1,所以打印:1211。


以此类推。(注意这里n是从1开始的)

问题求解:

class Solution {
public:
string countAndSay(int n) {
string ret = "1";//第一个序列
while(--n)
{//循环再得到n-1个序列
int count = 1;
string tmp;
for(int i=1;i<ret.size();i++)
{
if(ret[i] == ret[i-1]) count++;//如果相等,不断累加
else
{//如果不等,则把之前的字符个数和字符加到tmp,并将当前count置为1
tmp += to_string(count)+ret[i-1];
count = 1;
}
}
//跑完循环之后把最后一个字符加上,因为之前只完成到了对第i个字符的计数
tmp += to_string(count)+ret.back();//ret.back()取字符串中最后一个字符
ret = tmp;
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode