Queries to check if substring [ L ... R ] is palindrome or not | Java implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to answer every query in O ( 1 ) ; Driver code
class GFG { static int N = 100 ; static void pre_process ( boolean dp [ ] [ ] , char [ ] s ) { int n = s . length ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] = false ; } } for ( int j = 1 ; j <= n ; j ++ ) { for ( int i = 0 ; i <= n - j ; i ++ ) { if ( j <= 2 ) { if ( s [ i ] == s [ i + j - 1 ] ) { dp [ i ] [ i + j - 1 ] = true ; } } else if ( s [ i ] == s [ i + j - 1 ] ) { dp [ i ] [ i + j - 1 ] = dp [ i + 1 ] [ i + j - 2 ] ; } } } } static void answerQuery ( int l , int r , boolean dp [ ] [ ] ) { if ( dp [ l ] [ r ] ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { String s = " abaaab " ; boolean [ ] [ ] dp = new boolean [ N ] [ N ] ; pre_process ( dp , s . toCharArray ( ) ) ; int queries [ ] [ ] = { { 0 , 1 } , { 1 , 5 } } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) { answerQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , dp ) ; } } }