[ create a new paste ] login | about

Link: http://codepad.org/Q1KNTTrp    [ raw code | fork ]

C, pasted on Nov 11:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int validbrackets(char *str)
{
        char openers[] = {'(','{','[','<'};
        char closers[] = {')','}',']','>'};

        int counts[] = {0,0,0,0};

        int l = strlen(str);

        int *oldopeners = malloc(sizeof(int) * l);
        int oop_i = 0;

        for (int i = 0; i < l; ++i){
                for(int j = 0; j < 4; ++j){
                        if (str[i] == openers[j]){
                                counts[j]++;
                                oop_i++;
                                oldopeners[oop_i] = j;
                        } else if(str[i] == closers[j]){
                                if (oop_i <= 0 || j !=oldopeners[oop_i])
                                        return 0;
                                oop_i--;
                                counts[j]--;
                        }
                }

                for (int j = 0; j < 4; ++j){
                        if (counts[j] < 0)
                                return 0;
                }
        }

        for (int i = 0; i < 4; ++i){
                if (counts[i] != 0)
                        return 0;
        }

        return 1;
}

int main(int argc, char *argv[])
{
        if (argc != 2){
                printf("Use: cb str\n");
                return 0;
        }
        printf("%i\n", validbrackets(argv[1]));

        return 0;
}


Create a new paste based on this one


Comments: