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

posted @ 2019-06-04 09:47  lpomeloz  阅读(112)  评论(0编辑  收藏  举报