Share my C++ 0ms solution


  • -1
    J
    class Solution {
    public:
        string countAndSay(int n) {
            return recursion(n);
        }
        
        string recursion(int n){
            if(n==1)
            return "1";
            string s = recursion(n-1);
            string res="";
            char c = s[0];
            int count = 1;
            for(int i = 1;i<s.size();i++){
                if(c!=s[i]){
                    res+='0'+count;
                    res+=c;
                    c = s[i];
                    count =1;
                }
                else
                count++;
            }
            res+='0'+count;
            res+=c;
            return res;
        }
    };
    

    Actually, I dont know why the solution below runs 2ms?

    class Solution {
    public:
        string countAndSay(int n) {
                    if(n==1)
            return "1";
            string s = countAndSay(n-1);
            string res="";
            char c = s[0];
            int count = 1;
            for(int i = 1;i<s.size();i++){
                if(c!=s[i]){
                    res+='0'+count;
                    res+=c;
                    c = s[i];
                    count =1;
                }
                else
                count++;
            }
            res+='0'+count;
            res+=c;
            return res;
        }
    };

  • 0

    I think if count >= 10, your code may fail.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.