[Leetcode 33] 38 Count and Say
Problem:
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.
Analysis:
First of all, due to the large number of characters, integer is not enough to represent the result. Use string instead.
The basic algorithm is simple: maintaining a count for current characters while going through the given string. Every time a new character is accessed, if it's the same as the previous one, just increase the count by 1; If it's different from the previous one, add the count and the previous character into the result string and then set count to 1, character to current character. Repeat this process until the answer is got.
The time complexity is O(n), and space complexity is O(n)
Code:
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 string res("1"); 7 8 while (--n) { 9 say(res); 10 } 11 12 return res; 13 } 14 15 16 void say(string &s) { 17 int cnt = 1, idx = 0; 18 char val = s[0]; 19 string tmp(s); 20 s.resize(s.size()*2); 21 22 for (int i=1; i<tmp.size(); i++) { 23 if (tmp[i] != val) { 24 s[idx++] = cnt+'0'; 25 s[idx++] = val; 26 val = tmp[i]; 27 cnt = 1; 28 } else { 29 cnt++; 30 } 31 } 32 33 s[idx++] = cnt + '0'; 34 s[idx++] = val; 35 s.resize(idx); 36 } 37 };
Attention:
The manipulation of string in C++ is so hard... It took me very much time to finally make the code working.