LeetCode - Count and Say

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 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3474944.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值