Find index of closing bracket for a given opening bracket in an expression | C # 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
using System ; using System . Collections ; public class GFG { static void test ( String expression , int index ) { int i ; if ( expression [ index ] != ' [ ' ) { Console . Write ( expression + " , ▁ " + index + " : ▁ - 1 STRNEWLINE " ) ; return ; } Stack st = new Stack ( ) ; for ( i = index ; i < expression . Length ; i ++ ) { if ( expression [ i ] == ' [ ' ) { st . Push ( ( int ) expression [ i ] ) ; } else if ( expression [ i ] == ' ] ' ) { st . Pop ( ) ; if ( st . Count == 0 ) { Console . Write ( expression + " , ▁ " + index + " : ▁ " + i + " STRNEWLINE " ) ; return ; } } } Console . Write ( expression + " , ▁ " + index + " : ▁ - 1 STRNEWLINE " ) ; } public static void Main ( ) { test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) ; } }