38. Count and Say
Easy
6804923FavoriteShare
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
这题我一开始看了半天没看懂。。后面才理解
第一个输入是1,输出是1,这个不解释了
第二个输出就是在念第一个的输出,第一个输出是1,也就是1个1,所以输出11
第三个输出同理,11是2个1,所以是21,
第四个输出同理,21是由1个2和1个1组成,所以是1211
如此类推。。
本题理解了意思后就很好解决了,因为他题目说了n<=30,所以嘛。。。按顺序迭代下去就OK了
就是很直观的数出来就行。。。
例如
1211
我们就按顺序搞就行,一开始,只有1个1,于是就是11,只有1个2,于是是12,然后2个1,组合就说111221了。。
所以很直观的就是计算出连续序列的长度就行。。
代码如下
string countAndSay(int n)
{
string answer = "1";
int i = 1;
int counter = 1;
int j1 = 0;
while (i < n) {
string temp_string = "";
for (int j = 0; j < answer.size(); j++) {
int temp = answer[j] - 49;
j1 = j + 1;
while (j1 < answer.size() && answer[j] == answer[j1]) {
j = j1;
j1++;
counter++;
}
string t = to_string(counter);
temp_string.append(t);
temp_string.append(1,answer[j]);
counter = 1;
}
answer = temp_string;
i++;
}
return answer;
}
顺便装个B,竟然用时超过了100%的c++代码。。。不过用的空间确实比较大,懒得改了先这样吧