38. Count and Say

来源:互联网 发布:js去掉前面的空格 编辑:程序博客网 时间:2024/06/05 00:11

这里写图片描述
这道题开始开解错了题意,目标是求第n个数是几,而它是跟第n-1个数有关的
非递归法

class Solution {public:    string countAndSay(int n)     {        string s="1";        for(int i=0;i<n-1;i++)        {            int count=1;            int num=0,j;            char *a=new char[10000];            for(j=0;j+1<s.size();j++)            {                if(s[j]==s[j+1])                    count++;                else                {                    a[num++]=count%10+'0';                    count=count/10;                    a[num++]=s[j];                    count=1;                }            }            a[num++]=count%10+'0';            count=count/10;            a[num++]=s[j];            a[num]='\0';            s=a;            delete []a;        }        return s;    }};

递归法

class Solution {public:    string countAndSay(int n)     {        if(1==n)            return "1";        string s=countAndSay(n-1);        string temp="";        int count=1,j;        for(j=0;j+1<s.size();j++)        {            if(s[j]==s[j+1])                count++;            else            {                char c=count%10+'0';                temp=temp+c;                temp=temp+s[j];                count=1;            }        }        char c=count%10+'0';        temp=temp+c;        temp=temp+s[j];        return temp;    }};
0 0
原创粉丝点击