A simulation solution


  • 0
    L
    class Solution {
    public:
        string countAndSay(int n) {
    		if (n <= 0)
    			return string();
    
    		string ans = "1";
    		for (int i = 2; i <= n; ++i) {
    			string next;
    			char last = ans.front();
    			int cnt = 0;
    			auto pCh = ans.begin();
    
    			do {
    				if (pCh != ans.end() && last == *pCh) {
    					++cnt;
    				} else {
    					next.append(toString(cnt));
    					next.push_back(last);
    
    					last = *pCh;
    					cnt = 1;
    				}
    			} while (pCh++ != ans.end());
    
    			ans = next;
    		}
    		return ans;
        }
    private:
    	string toString(int n) const {
    		if (n < 0)
    			return string();
    		if (n == 0)
    			return "0";
    		string ans;
    		while (n) {
    			ans.push_back(n % 10 + '0');
    			n /= 10;
    		}
    		return move(string(ans.rbegin(), ans.rend()));
    	}
    };

Log in to reply
 

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