C program which is efficient and readable and also fastest program submitted so far


  • 0
    G
    char *create_seq (char *arr) 
    {
        char *result;
        int i, count=1, j=0, prev, curr, size;
        size = strlen(arr);
        /*
         * Allocate memory for the result with double the size of arr array
         */
        result = (char *)malloc(size*2);
        prev = curr = arr[0] - '0';
        /* 
         * logic is to calculate the count of digits you see 
         * by comparing prev and curr digit, and save the count and digit
         * in result string
         */
            for (i=1; i < size; i++) {
                    curr = arr[i] - '0';
                    if (prev == curr) {
                            count++;
                    } else {
                            result[j++] = count + '0';
                            result[j++] = prev + '0';
                            count = 1;
                    }
                    prev = curr;
            }
        /* 
         * last digit and its count is saved here 
         */
        result[j++] = count + '0';
        result[j++] = curr + '0';
        result[j] = '\0';
        return result;
    }                                                                                                                                                                
    char* countAndSay(int n) {                                                                                                                                       
        char *curr, *new;                                                                                                                                            
        int   i;                                                                                                                                                     
        /* 
         * start with string "1" 
         */
        curr = (char *)malloc(2);
        curr[0] ='1'; curr[1] = '\0';
        new = curr;
        for (i=2; i<=n; i++) {
            /*
             * Pass "curr" string and function will return "new" string 
             */
            new = create_seq(curr); 
            //printf("seq %d: '%s'\n", i, new);
            /*
             * free the curr string as we dont need it and 
             * save the new string in curr as thats what is used for next new string
             */
            free(curr);
            curr=new;
        }    
        return new;
    }
    
    

Log in to reply
 

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