-4

So I have an array full of brackets, for example :

1) (()())())((())(())

2) ()((()()))

Any open bracket ( '(' ) should also be closed by another one (')')

So for example 1) ->

(()())())((())(()) -> (....)..)((..)(..) -> ())(()() -> .)(.. , so the answer is no because from here we can see that not all of the brackets are balanced

For example 2) ->

()((()())) -> .((..)) -> (()) -> (..) -> () -> .. , so here the answer is yes because all brackets are balanced. In this case, I would also like to print the positions of all couples of brackets that are balanced, for example :

1,2 & 5,6 & 7,8 & 3,10 & 4,9

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Nson
  • 125
  • 1
  • 2
  • 11

2 Answers2

1

In your case, it's as simple using a counter. Increment for (, and decrement for ). It shouldn't go under 0, and should be 0 in the end if balanced.

You may consider using a stack, if you're creating some syntax parser like the compilers and interpreters do.

EDIT: you need to use a stack to print out the pairs. You need to implement a stack by hand in C, so the following is reference code in C++.

std::stack<int> s;
switch(string[i]) {
    case '(':
        s.push(i);
        break;
    case ')':
        if(!s.empty()) {
            printf("%d, %d\n", s.top(), i);
            s.pop();
        } else {
            // Fail here
        }
        break;
}
if(!s.empty()) // Fail here
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41
0

Count opening and closing brackets:

const char* it;
int         open_n = 0, close_n = 0;

/* Assume array is zero terminated. 
 * Otherwise condition: 'it != &array[ArraySize]' instead '*it' */

for(it = &array[0]; *it ; ++it) {
    switch( *it ) {
    case '(': open_n += 1; break;
    case ')': if( open_n ) { close_n += 1; break; }
              else         { return false; /* ErrorCloseWithoutOpen */ }
    default: break;
    }
}
return open_n ? false : true;
Frank-Rene Schäfer
  • 3,182
  • 27
  • 51