LeetCode:Count and Say
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.
题意:第一个输出:1 第二个输出:根据上一个的输出:“一个1”--->11
第三个输出:根据上一个的输出:“两个1”---->21
第四个输出:根据上一个的输出:“一个2,一个1”--->1211
第五个输出:根据上一个的输出:“一个1,一个2,两个1”--->111221
..............
string countAndSay(int n)
{
if(n == 1)
return "1";
string str = "1";
string res = "";
//把n个序列逐个求解
for(int i=1; i<=n; ++i)
{
for(int j=0; j<str.length(); )
{
int count = 0;
char c = str[j];
//判断一个字符连续出现的次数count
while(j<str.length() && c==str[j])
{
count++;
j++;
}
//将出现的个数count和字符进行组合成字符串
char tmp[3] = {0};
tmp[0] = count + '0';
tmp[1] = c;
tmp[2] = '\0';
res.append(tmp);
}
if(i == n-1)
return res;
// cout<<res<<endl;
str = res;
res = "";
}
}s算法比较二。。。死算出来的。
492

被折叠的 条评论
为什么被折叠?



