letecode [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 where 1 ≤ n ≤ 30, 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"

题目大意:

  根据题目规则,后一个数根据前一个数获得。如第1个数,读为1个1,则第2个数为11;第2个数读为2个1,则第3个数为21;第三个数读为1个2、1个1,则第四个数为1211.

  依次类推,输出第n个数的表示(字符串形式)。

理解:

  方法一:直观解法。从1开始求到第n个数。

      遍历第i个数的字符串,判断每个字符的连续出现次数,转换为第i+1个字符串的组成。

      注意,字符串末尾的处理,防止越界。其次,字符可以直接转换为字符串。

      但是,该解法的效率并不高。

  方法二:类似方法一,是参考其他人的代码。

      先递归到n =1,再往后求n。【感觉两种方法复杂度是一样的,但不知道为什么第二种方法效率要高很多】

代码C++:

  方法一: 

class Solution {
public:
    string countAndSay(int n) {
        if (n < 1 || n>30) return "";
        string str = "1";
        if (n == 1) return str;
        int i = 1, count, j;
        string newStr = "";
        while (i < n) {
            j = 0;
            while (str[j] != '\0') {
                count = 1;
                while (str[j] != '\0' && str[j] == str[j + 1]) {
                    ++j;
                    ++count;
                }
                newStr = newStr + to_string(count);
                newStr = newStr + str[j];

                ++j;
            }
            str = newStr;
            newStr = "";
            ++i;
        }
        return str;
    }
};

  方法二:

class Solution {
public:
    string countAndSay(int n) {
        if(n==1) return "1";
        string strlast=countAndSay(n-1);
        int count = 1;//计数
        string res;//存放结果
        for(int i=0;i<strlast.size();i++)
        {
            if(strlast[i]==strlast[i+1])//计算有多少个相同数字
            {
                count++;
                continue;
            }
            else
            {
                if(strlast[i]!=strlast[i+1])
                {
                    res+=to_string(count)+strlast[i];
                    count=1;
                }
            }
        }
       return res;
    }
};

 

运行结果:

  方法一:执行用时 : 52 ms  内存消耗 : 76.2 MB

  方法二:执行用时 : 8 ms    内存消耗 : 9.1 MB

转载于:https://www.cnblogs.com/lpomeloz/p/10968687.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值