Find an equal point in a string of brackets | Method to find an equal index ; Store the number of opening brackets at each index ; Store the number of closing brackets at each index ; check if there is no opening or closing brackets ; check if there is any index at which both brackets are equal ; Driver Code
< ? php function findIndex ( $ str ) { $ len = strlen ( $ str ) ; $ open = array ( 0 , $ len + 1 , NULL ) ; $ close = array ( 0 , $ len + 1 , NULL ) ; $ index = -1 ; $ open [ 0 ] = 0 ; $ close [ $ len ] = 0 ; if ( $ str [ 0 ] == ' ( ' ) $ open [ 1 ] = 1 ; if ( $ str [ $ len - 1 ] == ' ) ' ) $ close [ $ len - 1 ] = 1 ; for ( $ i = 1 ; $ i < $ len ; $ i ++ ) { if ( $ str [ $ i ] == ' ( ' ) $ open [ $ i + 1 ] = $ open [ $ i ] + 1 ; else $ open [ $ i + 1 ] = $ open [ $ i ] ; } for ( $ i = $ len - 2 ; $ i >= 0 ; $ i -- ) { if ( $ str [ $ i ] == ' ) ' ) $ close [ $ i ] = $ close [ $ i + 1 ] + 1 ; else $ close [ $ i ] = $ close [ $ i + 1 ] ; } if ( $ open [ $ len ] == 0 ) return $ len ; if ( $ close [ 0 ] == 0 ) return 0 ; for ( $ i = 0 ; $ i <= $ len ; $ i ++ ) if ( $ open [ $ i ] == $ close [ $ i ] ) $ index = $ i ; return $ index ; } $ str = " ( ( ) ) ) ( ( ) ( ) ( ) ) ) ) " ; echo ( findIndex ( $ str ) ) ; ? >