public static int [ ] balancePair ( String str , String left , String right ) { int count = 0 ; int offset = 0 ; int firstLeft = - 1 ; while ( true ) { int leftIndex = str . indexOf ( left , offset ) ; int rightIndex = str . indexOf ( right , offset ) ; if ( leftIndex == rightIndex ) { return new int [ ] { firstLeft , - 1 } ; } else if ( ( leftIndex < rightIndex && leftIndex != - 1 ) || rightIndex == - 1 ) { if ( firstLeft == - 1 ) { firstLeft = leftIndex ; } count ++ ; offset = leftIndex + 1 ; } else { count -- ; offset = rightIndex + 1 ; if ( count < 0 ) { return new int [ ] { firstLeft , - 1 } ; } if ( count == 0 ) { return new int [ ] { firstLeft , rightIndex } ; } } } }
Get the first balance pair substring index .