• 0 Posts
  • 3 Comments
Joined 1 year ago
cake
Cake day: July 23rd, 2023

help-circle

  • ISO C99:

    #include 
    #include 
    #include 
    #include 
    
    static char opener(char ch) {
        switch (ch) {
            case '}': return '{';
            case ']': return '[';
            case ')': return '(';
            default: return 0;
        }
    }
    
    enum { MAX_LINE_LENGTH = 2048 };
    static char buffer[MAX_LINE_LENGTH];
    
    int main(void) {
        char* line = fgets(buffer, sizeof(buffer), stdin);
        if (line == NULL) {
            fprintf(stderr, "Error: could not read input.\n");
            return EXIT_FAILURE;
        }
        size_t len = strlen(line);
        if (len > 0 and line[len - 1] == '\n') {
            line[--len] = 0;
        }
    
        char stack[128];
        size_t stack_size = 0;
        for (size_t i = 0; i < len; ++i) {
            char pair = opener(line[i]);
            if (pair and stack_size != 0 and stack[stack_size - 1] == pair) {
                --stack_size;
            } else {
                stack[stack_size++] = line[i];
            }
        }
        stack[stack_size] = 0;
        puts(stack);
    }
    

    Mirrored code on bpa.st

    Compile: cc -std=c99 -pedantic-errors -O2 bracket.c -o bracket

    (Edited to add -O2 because you mentioned it would be timed.)