1ms C master race (NSFL-LOOKING CODE)


  • -1
    G
    char* countAndSay(int n) {
        char *currentIteration = malloc(sizeof(int)*8);
        char *nextIteration = malloc(sizeof(int)*8);
        currentIteration[0] = '1';
        currentIteration[1] = 0;
        int count = 1;
        int nextIterationIndex = 0;
        int nextIterationMax = 8;
        int iterationsRemaining = n - 1;
        while(iterationsRemaining) {
            for (int i = 0; i < count; ) {
                char currentInteger = currentIteration[i];
                char currentIntegerCount = 1 + '0';
                i++;
                while (currentIteration[i] == currentInteger) {
                    currentIntegerCount++;
                    i++;
                }
                nextIteration[nextIterationIndex] = currentIntegerCount;
                nextIterationIndex++;
                nextIteration[nextIterationIndex] = currentInteger;
                nextIterationIndex++;
                if (nextIterationIndex >= nextIterationMax) {
                    nextIteration = realloc(nextIteration,sizeof(int)*2*nextIterationMax);
                    nextIterationMax *= 2;
                }
            }
            //printf("nextIterationIndex is %d\n",nextIterationIndex);
            nextIteration[nextIterationIndex] = 0;
            currentIteration = realloc(currentIteration,sizeof(int)*nextIterationMax);
            currentIteration = strdup(nextIteration);
            //printf("CURRENT ITERATION: %s\n",currentIteration);
            count = nextIterationIndex;
            //printf("count is %d\n",count);
            nextIterationIndex = 0;
            iterationsRemaining--;
        }
        free(nextIteration);
        return currentIteration;
    }

Log in to reply
 

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