simple C solution


  • 0
    W
    char* countAndSay(int n) {
        if(n<=0) return NULL;
        char *ret=(char *)calloc(2,sizeof(char));
        ret[0]='1';
        ret[1]='\0';
        int i=0,j=0,k=0;
        for(i=0;i<n-1;i++){
        	for(j=0;ret[j]!='\0';){
        		for(k=j+1;ret[k]!='\0';k++){
        			if(ret[j]!=ret[k]) break;
        		}
        		int tmp=k-j;
        		int slen=strlen(ret);
        		if(tmp==1){
        			ret=(char*)realloc(ret,(slen+2)*sizeof(char));
        			memmove(ret+k+1,ret+k,(slen-k+1)*sizeof(char));
        		}else{
        			memmove(ret+j+2,ret+k,(slen-k+1)*sizeof(char));
        		}
        		ret[j+1]=ret[j];
        		ret[j]=tmp+'0';
        		j=j+2;  		
        	}
        }
        return ret;
    }```

Log in to reply
 

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