题目: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.
该题目比较简单,代码如下:
// 时间复杂度 O(n^2),空间复杂度 O(n)class Solution {public: string CountAndSay(int n) { string sequ = "1"; for (int i = 1; i < n; ++i) { string tmp; for (int j = 0; ; ) { int counts = 1; while (j != sequ.size() -1 && sequ[j] == sequ[j + 1]) ++counts, ++j; tmp.push_back(counts + '0') tmp.push_back(sequ[j]); if (j == sequ.size() - 1) break; ++j; } sequ = tmp; } return sequ; }};新闻热点
疑难解答