报数-LintCode

来源:互联网 发布:网络歌手什么意思 编辑:程序博客网 时间:2024/05/26 02:55

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, …
1 读作 “one 1” -> 11.
11 读作 “two 1s” -> 21.
21 读作 “one 2, then one 1” -> 1211.
给定一个整数 n, 返回 第 n 个顺序。

注意事项:
整数的顺序将表示为一个字符串。

思路:
递归,在字符串中求数字连续出现的次数,据此,得出下一个字符串。

#ifndef C420_H#define C420_H#include<iostream>#include<string>using namespace std;class Solution {public:    /*    * @param n: the nth    * @return: the nth sequence    */    string countAndSay(int n) {        // write your code here        if (n <= 0)            return NULL;        if (n == 1)            return "1";        if (n == 2)            return "11";        string str = countAndSay(n - 1);        int len = str.size();        string res;        int count = 1;        for (int i = 0; i < len-1; ++i)        {            if (str[i] == str[i + 1])            {                count++;                if (i == len - 2)                {                    res += to_string(count);                    res += str[i];                }            }            else            {                res += to_string(count);                res += str[i];                if (i == len - 2)                {                    res += "1";                    res += str[len-1];                }                count = 1;            }        }        return res;    }};#endif
原创粉丝点击