Untitled

 avatar
unknown
plain_text
a year ago
855 B
3
Indexable
class Solution {
public:
    string solve(string s, int m) {
        // COnsecutuve same -> check for its freuqnecy and add, freq > 1
        // If they are not, athne add 1, char, freq = 1

        if (m == 0)
            return s;

        int n = s.length();
        int i = 0;

        string ans = "";
        if(n==1) 
        {
            ans+="1";
            ans+=s;
            return solve(ans, m-1);
        }

        while(i<n) {
            int freq = 0;
            char cur_char = s[i];
            while(i<n && s[i] == cur_char)
            {
                i++;
                freq++;
            }
            ans+=to_string(freq);
            ans.push_back(cur_char);
        }
        return solve(ans, m-1);
    }

    string countAndSay(int n) {
        if(n==1)
            return "1";

        return solve("1", n-1);
    }
};
Editor is loading...
Leave a Comment