你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

38. 外观数列——递归

2021/12/20 4:03:00
class Solution {
public:
    string countAndSay(int n) {
        string prev = "1";
        for(int i = 2; i <= n; i++){
            string curv = "";
            int start = 0;
            int num = 0;
            int j = 0;
            while(j < prev.size()){
                while(prev[j] == prev[start] && j < prev.size()){
                    j++;
                    num++;
                }
                curv = curv + to_string(num) + prev[start];
                start = j;
                num = 0;
            }
            prev = curv;
        }
        return prev;
    }
};

Accepted
30/30 cases passed (56 ms)
Your runtime beats 5.67 % of cpp submissions
Your memory usage beats 6.3 % of cpp submissions (118.4 MB)

class Solution {
public:
    string countAndSay(int n) {
        if(n == 1)
            return "1";
        string s = countAndSay(n - 1);
        string curv = "";
        int start = 0;
        int num = 0;
        for(int j = 0; j < s.size(); j++){
            if(s[j] == s[start] && j < s.size()){
                num++;
            }
            else{
                curv = curv + to_string(num) + s[start];
                start = j;
                num = 1;
            }
        }
        return curv + to_string(num) + s[start];
    }
};

Accepted
30/30 cases passed (28 ms)
Your runtime beats 11.05 % of cpp submissions
Your memory usage beats 5.01 % of cpp submissions (118.4 MB)