Simple C++ solution


  • 0
    P
        class Solution {
    public:
        string encode(string s){
            int n = s.length();
            int count = 1;
            char ch = s[0];
            string temp = "";
            int i=1;
            while(i<n){
                if(s[i]==ch){
                    count++;
                }
                else{
                    temp += (count+'0');
                    temp += ch;
                    ch = s[i];
                    count = 1;
                }
                if(i==n-1){
                    temp += (count+'0');
                    temp += ch;
                }
                i++;
            }
            return temp;
        }
        
        string countAndSay(int n) {
            if(n==0)    return "";
            else if(n==1)   return "1";
            else if(n==2)   return "11";
            
            string s = "11";
            int i = 3;
            while(i<=n){
                s = encode(s);
                i++;
            }
            return s;
        }
    };
    

Log in to reply
 

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