[recommend for beginners] easy C++ implementatoin


  • 0
    class Solution {
    public:
        string countAndSay(int n) {
            string s="1";
            for(int i=1; i<n; i++){
                int c=0;
                /** record the current checking char **/
                char ch='*';
                string temp;
                for(int j=0; j<s.size(); j++){
                    if(s[j]==ch) {
                        c++; 
                    }
                    else {
                        if(c>0)  temp+=(to_string(c)+ch); 
                        ch=s[j]; 
                        c=1;
                    }
                    /** corner cases **/
                    if(j==s.size()-1)  temp+=(to_string(c)+ch);
                }
                s=temp;
            }
            return s;
        }
    };

Log in to reply
 

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