题目
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 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 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"
解析
读完题后一时间不能理解是什么意思。其实题目原意是指一边数一边“读”,是根据上一个结果中数字的数量来决定当前结果。如n=4时,结果为1211,则n=5时,1211有1个1,1个2,2个1,拼到一起,则为111221,即是n=5时的结果。
因此,当n为任意正整数时,需要从1开始进行计算,逐个往后,依次做运算。
代码(C语言)
char* countAndSay(int n) {
if (n == 1)
return "1";
// 初始结果,即当n=1时
char* curRes = malloc(sizeof(char) * 2);
curRes[0] = '1';
curRes[1] = 0;
for (int i = 2; i <= n; ++i) {
unsigned long length = strlen(curRes);
char* temp = (char*)malloc(sizeof(char) * length * 3);
memset(temp, 0, 3 * length); // 声明的长度为当前长度*3,以防溢出
int count = 1, cursor = 0; // count为当前数字的数量,cursor为结果数组的指针
for (int index = 1; index < length; ++index) {
if (curRes[index] == curRes[index - 1]) { // 判断当前和前面的是否相同,相同则计数,不同则赋值
++count;
} else {
// 置位置
temp[cursor++] = count + '0';
temp[cursor++] = curRes[index - 1];
count = 1;
}
}
// 循环结束后,最后需要对结尾字符进行赋值
temp[cursor++] = count + '0';
temp[cursor] = curRes[length - 1];
free(curRes);
curRes = temp;
}
return curRes;
}
上述代码通过Xcode的编译,并且在LeetCode上Accepted。需要注意的是,当循环结束后需要对末尾字符进行赋值,释放内存,赋值上一次的结果,进行下一次的循环。