Solution in C++


  • 0
    P
    class Solution
    {
    public:
    	string countAndSay(int n) 
    	{
    		string ret = "1";
    		while (--n) 
    		{
    			string temp;
    			int len = ret.size(), count = 1;
    			for (int i = 0; i < len - 1; ++i)
    			{
    				if (ret[i] == ret[i + 1]) ++count;
    				else 
    				{
    					temp.push_back('0' + count);
    					temp.push_back(ret[i]);
    					count = 1;
    				}
    			}
    			temp.push_back('0' + count);
    			temp.push_back(ret[len - 1]);
    			std::swap(ret, temp);
    		}
    		return ret;
    	}
    };

Log in to reply
 

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