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.
这道计数和读法问题还是第一次遇到,看似挺复杂,其实仔细一看,算法很简单,就是对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。代码如下:
class Solution { public: string countAndSay(int n) { if (n <= 0) return NULL; string res = "1"; for (int i = 1; i < n; ++i) { string tmp; res.push_back('$'); // Add extra char to deal with boundary int count = 0; int len = strlen(res.c_str()); for (int j = 0; j < len; ++j) { if (j == 0) ++count; else { if (res[j] != res[j - 1]) { tmp.push_back(count + '0'); tmp.push_back(res[j - 1]); count = 1; } else ++count; } } res = tmp; } return res; } };
在我的代码里,对每个之前的string结尾加入了个额外的字符,这样做的原因是,我每次比较的是当前元素和之前那个是否相同,然后把之前元素存到新string里,而当前元素的处理是在下一次循环中完成的。当加入一个额外无用字符后,当循环到最后这个额外字符后,前一个有用字符处理完之后就可以结束循环了。
我出于好奇打印出了前12个数字,发现一个很有意思的现象,不管打印到后面多少位,出现的数字只是由1,2和3组成,网上也有人发现了并分析了原因 (http://www.cnblogs.com/TenosDoIt/p/3776356.html),前十二个数字如下:
1 1 1 2 1 1 2 1 1 1 1 1 2 2 1 3 1 2 2 1 1 1 3 1 1 2 2 2 1 1 1 1 3 2 1 3 2 1 1 3 1 1 3 1 2 1 1 1 3 1 2 2 1 1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1 1 1 1 3 1 2 2 1 1 3 3 1 1 2 1 3 2 1 1 3 2 1 2 2 2 1 3 1 1 3 1 1 2 2 2 1 2 3 2 1 1 2 1 1 1 3 1 2 2 1 1 3 1 2 1 1 3 2 1 1