LeetCode 38. Count and Say

题目

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 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。需要注意的是,当循环结束后需要对末尾字符进行赋值,释放内存,赋值上一次的结果,进行下一次的循环。

运行结果

n=1-13的运行结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,921评论 0 23
  • 补发2月9日的。
    墙内宅人呆阅读 401评论 0 0
  • 午休时候,睡到昏死,还做了很长的梦, 在梦里,我又回到了敦煌莫高窟,每个洞窟里的佛祖都是三维立体,每个洞窟里都有红...
    彼得潘潘阅读 347评论 0 1
  • 真佩服我自己了 睡了三个小时了还没睡着 简直是胡思乱想 这样下去我是不是要开点安眠药了 事业、家庭、爱情、 想了几...
    抱抱酱iPhone99阅读 171评论 1 0