从零开始的LC刷题(12): 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"

看了题很懵逼,遂百度了一下,发现意思就是2是在1的基础上得来的,3是来自于2的读法的以此类推,那个博客正好写了代码我就按他的思想(没有算法)写了代码出来,发现性能弱鸡内存占用又高,我就把递归改成循环调用结果性能还是很辣鸡,结果如下:

Success

Runtime: 32 ms, faster than 15.33% of C++ online submissions for Count and Say.

Memory Usage: 59 MB, less than 15.92% of C++ online submissions for Count and Say.

代码:

class Solution {
public:
    string countAndSay(int n) {
        string str="";
        string r="1";
        for(int s=0;s<n-1;s++){
            str=r;
            r="";
            for(int i=0;i<str.size();i++)
            {
                int m=1;
                while(str[i+1]==str[i]){i++;m++;}
                r=r+to_string(m)+str[i];
            }
        }
        return r;
    }
    
};

之后发现我蠢了,r=r+to_string(m)+str[i];应该写成r+=to_string(m)+str[i];,结果就变成:

Success

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Count and Say.

Memory Usage: 8.9 MB, less than 61.26% of C++ online submissions for Count and Say.

猜你喜欢

转载自blog.csdn.net/cyr429/article/details/89513641
今日推荐