0ms C language Solution


  • 5
    N
    char* countAndSay(int n) {
        if( n == 1 ) return "1";
    	char *cur = malloc(2), *tmp;
    	cur[0] = '1';
    	cur[1] = 0;
    	
    	int len, idx, j, count;
    	for(int i = 2; i <= n; ++i)
    	{
    		len = strlen(cur);
    		tmp = malloc(len * 3);
    		memset(tmp, 0, len * 3);
    		count = 1;
    		for(idx = 1, j = 0; idx < len; ++idx)
    		{
    			if(cur[idx] == cur[idx-1])
            	{
                	++count;
            	}
    			else
            	{
                	tmp[j++] = '0' + count;
                	tmp[j++] = cur[idx-1];
                	count = 1;
            	}
    		}//end of for
    		tmp[j++] = '0' + count;
        	tmp[j++] = cur[len-1];
    		free(cur);
    		cur = tmp;
    	}	
    	return cur;
    }

  • 0
    U

    Why set ''tmp = malloc(len * 3);''?


  • 0
    C

    my C solution!

     char* countAndSay(int n) {
        
        int i,j;
      
        int count;
        
        char *cur = (char *)malloc(1024*20*sizeof(char));
       
        char *next = (char *)malloc(1024*20*sizeof(char));
       
        cur[0]='1';cur[1]='\0';
        while(--n){
            i=0;j=0;
            while(cur[i]!='\0'){
                count=1;
                while(cur[i]==cur[i+1]){
                    i++;count++;
                }
                next[j++]=count+'0';
                next[j++]=cur[i];
                i++;
            }
            next[j]='\0';
            strcpy(cur,next);
        }
        return cur;
    }

  • 1
    F

    the new space needed is at most

     2 * strlen(cur) + 1
    

    if every char in cur is different from their neighbors., ex,:

    "23121"  ==> "1213111211"

Log in to reply
 

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