首页 > 学院 > 开发设计 > 正文

51:Count and Say

2019-11-06 08:51:18
字体:
来源:转载
供稿:网友

题目: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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表