Share C++ 2ms ,using an end char '#',very easy to understand


  • 1
    W
        class Solution {
    public:
    	string countAndSay(int n) {
    		if(n==0) return string();
    		if(n==1) return string("1");
    
    		// use of the end char '#'
    		string sqence("1#");
    		string tempStr;
    		for (int i=1; i<n; ++i)
    		{
    			tempStr.clear();
    			int cnt = 1;
    			for(int j=0; j<sqence.size()-1; ++j)
    			{
    				if(sqence[j] == sqence[j+1])
    				{
    					++cnt;
    				}
    				else
    				{
    					tempStr.push_back('0'+cnt);
    					tempStr.push_back(sqence[j]);
    					cnt = 1;
    				}
    			}
    			sqence = tempStr;
    			sqence.push_back('#'); // every time push the end char
    		}
    
    		// pop the end char '#'
    		sqence.pop_back();
    		return sqence;
    	}
    };

Log in to reply
 

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