My accepted simple solution in C++,Any advising?


  • 0
    K
    class Solution {
    public:
    	//1211
        string countAndSay(int n) 
        {
            vector<string> ret(n,"");
            if(n<1) 
                return "";
            else if(1==n)
                return "1";
            else
            { 
                ret[0]="1";
                for(int i=1;i<n;i++)
                {
                    for(int j=0;j<ret[i-1].size();j++)
                    {
                        //int start=j;
    					int cnt=1;
    					while((j+1)<ret[i-1].size()&&ret[i-1][j]==ret[i-1][j+1])
    					{
    						cnt++;
    						j++;
    					}
    					ret[i]=ret[i]+(char)(cnt+'0')+ret[i-1][j];
                    }
                }
                return ret[n-1];
            }
          
        }
    };

  • 0
    A

    I do not think vector of string is required. You are wasting memory. You can do use two strings.


Log in to reply
 

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