Print the longest palindromic prefix of a given string | C ++ program for the above approach ; Function to find the longest prefix which is palindromic ; Find the length of the given string ; For storing the length of longest prefix palindrome ; Loop to check the substring of all length from 1 to N which is palindrome ; String of length i ; To store the reversed of temp ; Reversing string temp2 ; If string temp is palindromic then update the length ; Print the palindromic string of max_len ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void LongestPalindromicPrefix ( string s ) { int n = s . length ( ) ; int max_len = 0 ; for ( int len = 1 ; len <= n ; len ++ ) { string temp = s . substr ( 0 , len ) ; string temp2 = temp ; reverse ( temp2 . begin ( ) , temp2 . end ( ) ) ; if ( temp == temp2 ) { max_len = len ; } } cout << s . substr ( 0 , max_len ) ; } int main ( ) { string str = " abaab " ; LongestPalindromicPrefix ( str ) ; }