420 报数

原题网址:https://www.lintcode.com/problem/count-and-say/description

描述

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:

1, 11, 21, 1211, 111221, ...

1 读作 "one 1" -> 11.

11 读作 "two 1s" -> 21.

21 读作 "one 2, then one 1" -> 1211.

给定一个整数 n, 返回 第 n 个顺序。

整数的顺序将表示为一个字符串。

您在真实的面试中是否遇到过这个题?  

样例

给定 n = 5, 返回 "111221".

标签
字符串处理

 

思路:读题读了半天才理解啥意思……囧。

简而言之,当前数是前一个数的报数(读法),也就是统计前一个字符串的单个字符出现次数+单个字符本身,最后构成一个新串。

可以用循环来做,也可以用递归来做。

循环AC代码:

class Solution {
public:
    /**
     * @param n: the nth
     * @return: the nth sequence
     */
    string countAndSay(int n) {
        // write your code here
    
    if (n<=0)
    {
        return "";
    }
    string result="1";
    for (int ind=2;ind<=n;ind++)
    {
        int size=result.size(),i=0,j=0;
        string tmp="";
        for (;i<size;)
        {
            char c=result[i];
            int count=1;
            for (j=i+1;j<size;)
            {
                if (c==result[j])
                {
                    count++;
                    j++;
                }
                else
                {
                    break;
                }
            }
            string s;
            int2str(count,s);//count转成string;
            tmp=tmp+s+c;
            i=j;
        }
        result=tmp;
    }

    return result;
    
    
    }
    
    void int2str(const int &int_tmp,string &string_tmp)
{
    stringstream s;
    s<<int_tmp;
    string_tmp=s.str();//或者 s>>string_tmp;
}
};

 

递归AC代码:

class Solution {
public:
    /**
     * @param n: the nth
     * @return: the nth sequence
     */
    string countAndSay(int n) {
        // write your code here
    
   if (n<=0)
    {
        return "";
    }
    if (n==1)
    {
        return "1";
    }
    string result="";
    string preresult=countAndSay(n-1);
    int size=preresult.size(),i=0,count=1,j=0;
    for (;i<size;)
    {
        char c=preresult[i];
        count=1;
        for (j=i+1;j<size;)
        {
            if (c==preresult[j])
            {
                count++;
                j++;
            }
            else
            {
                break;
            }
        }
        string s;
        int2str(count,s);
        result=result+s+c;
        i=j;
    }
    return result;
    
    
    }
    
    void int2str(const int &int_tmp,string &string_tmp)
{
    stringstream s;
    s<<int_tmp;
    string_tmp=s.str();//或者 s>>string_tmp;
}
};

 

 

 

 

posted @ 2018-06-25 13:37  eeeeeeee鹅  阅读(242)  评论(0编辑  收藏  举报