Precompute the prefix 2D array
for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < MAX_CHAR ; j ++ ) l [ j ] [ i ] += l [ j ] [ i - 1 ] ; l [ s [ i ] - ' a ' ] [ i ] ++ ; } r [ s [ n - 1 ] - ' a ' ] [ n - 1 ] = 1 ;