题目:
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, 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"
解题思路:这道题看起来似乎很玄妙。实际上,只需要注意两个东西即可。一个是当前所读到的数字,另一个是数一共有几个数是与当前所读数字相同且连续的。记录下这两个东西即可。新的字符串中,先插入后者所数到的数目,再插入所读到的数字,依次迭代即可。
代码如下:
class Solution {
public:
string countAndSay(int n) {
string result = "1";
string result2 = "";
if (n == 1)
return "1";
for (int i = 0; i < n-1; i++) {
int count = 1;
int j;
char count_;
for (j = 0; j < result.length()-1; j++) {
if (result[j] == result[j+1]) {
count++;
} else {
count_ = count+48;
result2 = result2+count_+result[j];
count = 1;
}
}
count_ = count+48;
result2 = result2+count_+result[j];
result = result2;
result2 = "";
}
return result;
}
};