Navin Chauhan Navin Chauhan - 9 days ago 7
C Question

Storing address of opening and closing of bracket

If the user gives me a string of any combination of brackets like

(()())
then I want a program which checks the opening and closing of the bracket and also stores the address of opening and closing of each bracket separately in an arranged way. How can I do it?

Answer

In the case of a type of bracket is one kind, it is not necessary to save something just by increasing or decreasing the counter.

Examples like the following

#include <stdio.h>
#include <stdbool.h>

bool isBalanceBracket(const char *s){
    int count = 0;
    for(int i = 0; s[i] ; ++i){
        if(s[i] == '(')
            ++count;
        else if(s[i] == ')')
            if(--count < 0)
                return false;
    }
    return count == 0;
}

int main(void){
    const char *test[] = {
        "(()())", ")()(", "()))"
    };
    for(int i = 0; i < sizeof(test)/sizeof(*test); ++i){
        if(isBalanceBracket(test[i]))
            printf("%s is OK\n", test[i]);
        else
            printf("%s is NG\n", test[i]);
    }
    return 0;
}
Comments