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