美文网首页
Leetcode 38. Count and Say

Leetcode 38. Count and Say

作者: persistent100 | 来源:发表于2017-04-27 17:44 被阅读0次

    题目

    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. 1
      
    2. 11
      
    3. 21
      
    4. 1211
      
    5. 111221 
      
    6. 312211
      
    7. 13112221
      
    8. 1113213211
      
    9. 31131211131221
      
    10. 13211311123113112211
      需要找出第N个序列,本来一直想找规律,结果找不到,只有最慢的方法,依次解析字符,从1到第N个依次计算,最后得出结果。
      C代码如下,已通过。
    char* countAndSay(int n) {
        char * ans=(char *)malloc(sizeof(char)*100000);
        ans[0]='1';
        ans[1]='\0';
        for(int i=1;i<n;i++)
        {
            char *temp=(char *)malloc(sizeof(char)*100000);
            int k=0;
            while(ans[k]!='\0')
            {
                temp[k]=ans[k];
                k++;
            }
            temp[k]='\0';
            //printf("temp:%s\n",temp);
            char left=' ';
            int num=1,ansLength=0;
            for(int j=0;j<k;j++)
            {
                if(temp[j]==left)
                {
                    num++;
                }
                else
                {
                    if(left!=' ')
                    {
                        ans[ansLength]=num+'0';
                        ansLength++;
                        ans[ansLength]=left;
                        ansLength++;
                        num=1;
                    }
                    left=temp[j];
                }
            }
            ans[ansLength]=num+'0';
            ansLength++;
            ans[ansLength]=left;
            ansLength++;
            ans[ansLength]='\0';
            //printf("ans:%s\n",ans);
            free(temp);
        }
        return ans;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 38. Count and Say

          本文链接:https://www.haomeiwen.com/subject/xbrnzttx.html