首页 > 代码库 > Count and Say

Count and Say

class Solution {
public:
    string countAndSay(int n) {
        string ret = "1";
        for(int i=1; i<n; ++i)
            ret = generateNext(ret);
        return ret;
    }
    
    string generateNext(string s)
    {
        string ret = "";
        for(int i=0; i<s.size(); ++i)
        {
            int count = 1;
            while((i<s.size()-1) && s[i] == s[i+1])
            {
                ++count;
                ++i;
            }
            ret.insert(ret.end(), count + 0);
            ret.insert(ret.end(), s[i]);
            
        }
        
        return ret;
    }
};

 

Count and Say