您的位置:首页 > 其它

LeetCode 38:Count and Say

2015-12-23 15:09 281 查看
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
1"
 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, 11, 21, 1211, 111221, ...

1 读作"一个1" 或者11 (1个1)

11 读作"两个1" 或者21 (2个1)

21 读作"一个2,然后是一个1" 或者1211 (1个2,1个1)

给定一个整数n,返回第n个"数和说"序列

注意:返回的整数序列应当作用一个字符串表示

第一次写出一次通过的代码。。。虽然是很简单的题目但还是很高兴←_←思路就是从左往右读,读到不一样的就记录前面读到的个数和数字,然后接着读。。。

class Solution {
public:
string countAndSay(int n) {
string temp="1";
for(int i=1;i<n;i++)
{
string temp1;
int num=temp[0]-'0';
int count=0;
for(int j=0;j<temp.length();j++)
{
if(temp[j]-'0'==num)
count++;
else
{
temp1.append(to_string(count));
temp1.push_back(num+'0');
num=temp[j]-'0';
count=1;
}
}
temp1.append(to_string(count));
temp1.push_back(num+'0');
temp=temp1;
}
return temp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: