问题描述:
思路简述:
首先没考虑递归,直接按时序来写发现思路有点混乱,用递归的话可以集中思路来解决这样的核心问题:"比如给字符串111 则返回字符串31;给字符串12 返回1112 ",相比思路会更加清晰,但是时间和空间复杂度确实不太理想。另外用纯C语言来写的话对于数组下标越界细节要多加注意;动态创建a数组时,之前数组长度给定的n莫名其妙越界直接和b一样给了个2n索性过了。
char* describe(char * str) {
int n = strlen(str);
int* a = (int*)calloc(n*2, sizeof(int));
int* b = (int*)calloc(n*2, sizeof(int));
for (int i = 0; i < n; i++) {
a[i] = str[i] - '0';
}
int resultLen = 0;
int count = 1;
for (int i = 1; i <= n; i++) {
if (a[i] == a[i - 1]) {
count ++;
}
else {
b[resultLen] = count;
b[resultLen + 1] = a[i - 1];
resultLen += 2;
//printf("%d 个 %d\n", count, a[i-1]);
count = 1;
}
}
char* result = (char*)calloc(resultLen+1, sizeof(char));
for (int i = 0; i < resultLen; i++) {
result[i] = b[i] + '0';
}
result[resultLen] = '\0';
return result;
}
char * countAndSay(int n) {
if (n == 1) return "1";
else {
return describe(countAndSay(n - 1));
}
}