LC 38. Count and Say

Nilanjan Deb · April 1, 2020

I got this problem from BITS CSD course ,then I solved this Problem using CPP. Solution algorithm is very easy. I thought this Solution is self understandable. I used a vector of int type to store the elements of series each an every step and a empty vector of int type to store the next element and count the digits in current element. Then after geting the nth element I transform it to string and return it to the main().

class Solution {
public:
    string countAndSay(int n) {
        vector <int> k;
        k.push_back(1);
        vector <int> ans ;
        for(int j=1;j<n;j++){
            int cnt = 1;
            for(int i = 0;i < k.size()-1;i++){ 
                if(k[i] == k[i+1]){
                    cnt+=1;
                }
                else{
                    ans.push_back(cnt);
                    ans.push_back(k[i]);
                    cnt = 1;
                }
            }
            ans.push_back(cnt);
            ans.push_back(k[k.size()-1]);
            k  = ans;
            ans.clear();
        }
        char result[k.size()+1];
        for(int i = 0;i < k.size();i++){
            result[i] = k[i] + '0';
        }
        result[k.size()] = '\0';
        string res = result;
        return res;
    }
};


Dicussion Forum