您的位置:首页 > 其它

Leetcode--Count and Say

2014-10-17 16:20 267 查看
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=1时,输出字符串为1

n=2时,输出字符串为11(表示前一个字符串中有1个1)

n=3时,输出字符串为21(表示前一个字符串中有2个1)

n=4时,输出字符串为1211(表示前一个字符串中有1个2,1个1)

....

可以发现输出结果是前一个字符串的各个数字字符的个数(个数+字符)

class Solution {
public:
string countAndSay(int n) {
string tmp="1";
for(int i=1;i<n;i++)
{
string stmp="";
for(int j=0;j<tmp.size();j++)
{
int k=j+1;
while(k<tmp.size()&&tmp[j]==tmp[k]) k++;
stringstream stream;
stream<<(k-j);
string ss;
stream>>ss;
stmp+=ss;
stmp+=tmp[j];
j=k-1;
}
tmp=stmp;
}
return tmp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: