[leetcode]Count and Say (伯爵说 C语言实现)

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.
题意:伯爵说,
1读为“一个1”输出11
11读为“两个1”输出21
………..
给定一个n,输出第n个字符串序列
Notes:整型序列用字符串表示。
解题思路:这涉及的知识点是字符串的操作,字符串转整型,还有就是细节问题,对最后一个字符的操作,对相同字符的统计并作为下一个字符串的字符。
C语言实现代码:

/**
 * 解题思路:涉及到字符串的简单操作,需要获取字符串中相同字符的个数并作为下一个字符串的字符
 * 输入的n代表去第几个字符串输出,这同时也需要求出前面字符串的值,就行Fibonacci数列一样,求后一个字符串需要知道前一个字符串
 */
void CountSay(char *str1, char *str2){
    int count, i, j;
    count = 1;
    j = i = 0;
    while(*(str1+i+1) != '\0'){
        if(*(str1+i) == *(str1+i+1)){
            i++;
            count++;
        }else{
            *(str2 + j++) = count + '0';
            *(str2 + j++) = *(str1+i);
            i++;
            count = 1;
        }
    }
    *(str2 + j++) = count + '0';
    *(str2 + j++) = *(str1+i);
}

char *countAndSay(int n) {
    char *str1, *str2;
    int i;
    str1 = (char *)malloc(9999*sizeof(char));//初始化数组大小
    str2 = (char *)malloc(9999*sizeof(char));
    memset(str1, 0 ,9999);
    memset(str2, 0, 9999);
    strcpy(str2, "1");
    for(i = 1; i return str2;
}

你可能感兴趣的:(leetcode)