Maximum length palindromic substring such that it starts and ends with given char | Function that returns true if str [ i ... j ] is a palindrome ; Function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch ; If current character is a valid starting index ; Instead of finding the ending index from the beginning , find the index from the end This is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop ; If current character is a valid ending index ; If str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far ; Driver code
function isPalindrome ( str , i , j ) { while ( i < j ) { if ( str [ i ] !== str [ j ] ) { return false ; } i ++ ; j -- ; } return true ; } function maxLenPalindrome ( str , n , ch ) { var maxLen = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( str [ i ] === ch ) { for ( var j = n - 1 ; j >= i ; j -- ) { if ( str [ j ] === ch ) { if ( isPalindrome ( str , i , j ) ) { maxLen = Math . max ( maxLen , j - i + 1 ) ; break ; } } } } } return maxLen ; } var str = " " ; var n = str . length ; var ch = " " ; document . write ( maxLenPalindrome ( str , n , ch ) ) ;