Count and Say

Total Accepted: 63607 Total Submissions: 237192 Difficulty: Easy

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

 
class Solution {
public:
    string countAndSay(int n) {
        string s = "";
        string res = s;
        for(int i=0;i<n;i++){
            res = "";
            int cnt = 1;
            for(int j=1;j<s.size();j++){
                if(s[j]==s[j-1]){
                    cnt++;
                }else{
                    res.push_back(cnt+'0');
                    res.push_back(s[j-1]);
                    cnt = 1;
                }
            }
            res.push_back(cnt+'0');
            if(!s.empty())
               res.push_back(s[s.size()-1]);
            s = res;
        }
        cout<<res<<endl;
        return res;
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/5035790.html