traversing string from the end .
for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == ' [ ' ) { Vector < Character > s = new Stack < Character > ( ) ; while ( arr . peek ( ) != ' ] ' ) { s . add ( arr . peek ( ) ) ; arr . pop ( ) ; } arr . pop ( ) ;