Find index of closing bracket for a given opening bracket in an expression | Java 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
import java . util . Stack ; class GFG { static void test ( String expression , int index ) { int i ; if ( expression . charAt ( index ) != ' [ ' ) { System . out . print ( expression + " , ▁ " + index + ": -1NEW_LINE"); return ; } Stack < Integer > st = new Stack < > ( ) ; for ( i = index ; i < expression . length ( ) ; i ++ ) { if ( expression . charAt ( i ) == ' [ ' ) { st . push ( ( int ) expression . charAt ( i ) ) ; } else if ( expression . charAt ( i ) == ' ] ' ) { st . pop ( ) ; if ( st . empty ( ) ) { System . out . print ( expression + " , ▁ " + index + " : ▁ " + i + "NEW_LINE"); return ; } } } System . out . print ( expression + " , ▁ " + index + ": -1NEW_LINE"); } public static void main ( String [ ] args ) { test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) ; } }