Count and Say
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.
» Solve this problem不知道怎么回事,用strcat就老是会有run error。
class Solution { public: char buf[10000]; char dest[10000]; string countAndSay(int n) { buf[0] = '1'; buf[1] = '\0'; for (int i = 1; i < n; i++) { convert(buf, dest); memcpy(buf, dest, sizeof(buf)); } return string(buf); } void convert(char* src, char* dest) { char num[10000]; int cnt[10000]; memset(cnt, 0, sizeof(cnt)); memset(num, 0, sizeof(num)); int idx = -1; int len = strlen(src); char *s = src, *end = src + len; char prev = 'x'; while (s != end) { if (prev == *s) { cnt[idx]++; } else { cnt[++idx] = 1; num[idx] = *s; prev = *s; } s++; } int id = 0; char tmp[32]; for (int i = 0; i <= idx; i++) { dest[id++] = cnt[i] + '0'; dest[id++] = num[i]; } dest[id] = '\0'; return; } };