随笔- 509  文章- 0  评论- 151  阅读- 22万 

Count and Say

2013.12.15 03:00

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.

Solution:

  Just do as the problem description says, count and say.

  Time complexity is...?

  Let's consider two cases:

    11111->51

    12345->1112131415

  We'll have to calculate all the sequences s[1], s[1], ..., s[n - 1] before getting s[n]. Thus the time complexity is O(len(s[1]) + len(s[2]) + ... + len(s[n -1])), the average rate of growth of s[i] is between (0, 2), thus the time complexity can be roughly O(2^n).

  Space complexity is O(2^n) too, as string buffer needs extra space.

  I'm quite sure that n cannot be very large, otherwise it won't run on an OJ (u_u)

Accepted code:

复制代码
 1 // 1CE, 1AC
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     string countAndSay(int n) {
 8         // IMPORTANT: Please reset any member data you declared, as
 9         // the same Solution instance will be reused for each test case.
10         string res = "1";
11         
12         for(int i = 1; i < n; ++i){
13             res = nextSequence(res);
14         }
15         
16         return res;
17     }
18 private:
19     char buf[100];
20     string nextSequence(string cur) {
21         string res;
22         int i, j;
23         int len = cur.length();
24         
25         res = "";
26         i = 0;
27         while(i < len){
28             j = i + 1;
29             while(j < len && cur[i] == cur[j]){
30                 ++j;
31             }
32             // 1CE here, you can't simply concatenate string with other data type...
33             // use sprintf or sstream to do this
34             sprintf(buf, "%d%c", j - i, cur[i]);
35             res = res + string(buf);
36             i = j;
37         }
38         
39         
40         return res;
41     }
42 };
复制代码

 

 posted on   zhuli19901106  阅读(722)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示