这题用到的字符串数组要很大的空间,我这里用了5000,小了不够。代码上有一些注释。
大概思想是,最初始是只有一个“1”,然后对他进行描述,描述过程:对字符挨个遍历,相同进行计数,指导不同的,然后把计数count和该字符放进临时字符数组temp,全部遍历完。把temp赋值给s,然后继续遍历s。
int revers(int n) {
//把12放进数组要先放高位,最后放个位
int sum = 0;
while (n != 0) {
sum = sum * 10 + n % 10;
n /= 10;
}
return sum;
}
char *countAndSay(int n) {
char *s = (char *) malloc(sizeof(char) * 5000);
char *temp = (char *) malloc(sizeof(char) * 5000); //临时数组
memset(s, '\0', sizeof(s));
s[0] = '1';
for (int i = 1; i < n; ++i) {
memset(temp, '\0', sizeof(char) * 5000);
int j = 0;
int k = 0;
int count = 0; //当前字符的个数
while (s[j] != '\0') {
char c = s[j]; //当前判断的字符
while (c == s[j]) {
//进行数数
count++;
j++;
}
while (revers(count) != 0) {
//这一步把数字次数放进字符串
//进行这步是因为万一有大于出现10次的
int t = count % 10;
temp[k++] = t + '0';
count /= 10;
}
temp[k++] = c;
}
strcpy(s, temp);
}
free(temp);
return s;
}
还没有进行优化。暴力好理解。