Find index of closing bracket for a given opening bracket in an expression | CPP program to find index of closing bracket for given opening bracket . ; Function to find index of closing bracket for given opening bracket . ; If index given is invalid and is not an opening bracket . ; Stack to store opening brackets . ; Traverse through string starting from given index . ; If current character is an opening bracket push it in stack . ; If current character is a closing bracket , pop from stack . If stack is empty , then this closing bracket is required bracket . ; If no matching closing bracket is found . ; Driver Code ; should be 8 ; should be 7 ; should be 12 ; No matching bracket
#include <bits/stdc++.h> NEW_LINE using namespace std ; void test ( string expression , int index ) { int i ; if ( expression [ index ] != ' [ ' ) { cout << expression << " , ▁ " << index << " : ▁ - 1 STRNEWLINE " ; return ; } stack < int > st ; for ( i = index ; i < expression . length ( ) ; i ++ ) { if ( expression [ i ] == ' [ ' ) st . push ( expression [ i ] ) ; else if ( expression [ i ] == ' ] ' ) { st . pop ( ) ; if ( st . empty ( ) ) { cout << expression << " , ▁ " << index << " : ▁ " << i << " STRNEWLINE " ; return ; } } } cout << expression << " , ▁ " << index << " : ▁ - 1 STRNEWLINE " ; } int main ( ) { test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) ; return 0 ; }