The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
AC code:
class Solution {
public:
string countAndSay(int n) {
vector<string> v;
init(v, n);
return v[n-1];
}
void init(vector<string>& v, int n) {
v.push_back("1");
for (int i = 1; i <= n; ++i) {
string res = v[i-1];
char c = res[0];
string ans = "";
int num = 1;
for (int i = 1; i < res.length(); ++i) {
if (res[i] == c) {
num++;
continue;
} else {
ans = ans + to_string(num) + c;
c = res[i];
num = 1;
}
}
ans = ans + to_string(num) + c;
v.push_back(ans);
}
}
};
Runtime: 8 ms, faster than 8.70% of C++ online submissions for Count and Say.
class Solution {
public:
std::string countAndSay(int n) {
if (0 == n) return "";
if (1 == n) return "1";
std::string res="1";
std::string s;
for (int i = 1; i < n; i++){ // run from starting to generate second string
int len = res.size();
//cheack all digits in the string
for (int j = 0; j < len; j++){
int count=1; // we have at least 1 occourence of each digit
// get the number of times same digit occurred (be carefull with the end of the string)
while ((j + 1 < len) && (res[j] == res[j + 1])){
count++;
j++; // we need to keep increasing the index inside of the string
}
// add to new string "count"+"digit itself"
s += std::to_string(count) + res[j];
}
// save temporary result
res = s;
// clean our string-helper
s.clear();
}
return res;
}
};
Runtime:
4 ms, faster than 41.19% of C++ online submissions for Count and Say.
char* countAndSay(int n) {
if( n == 1 ) return "1";
char *cur = malloc(2), *tmp;
cur[0] = '1';
cur[1] = 0;
int len, idx, j, count;
for(int i = 2; i <= n; ++i)
{
len = strlen(cur);
tmp = malloc(len * 3);
memset(tmp, 0, len * 3);
count = 1;
for(idx = 1, j = 0; idx < len; ++idx)
{
if(cur[idx] == cur[idx-1])
{
++count;
}
else
{
tmp[j++] = '0' + count;
tmp[j++] = cur[idx-1];
count = 1;
}
}
tmp[j++] = '0' + count;
tmp[j++] = cur[len-1];
free(cur);
cur = tmp;
}
return cur;
}
Runtime: 0 ms, faster than 100.00% of C online submissions for Count and Say.