Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | C ++ implementation of the approach ; Function that returns true if s is palindrome ; Function to return the required index ; Copy the ith character in S ; Copy all the character of string s2 in Temp ; Check whether the string is palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string s ) { int i = 0 ; int j = s . length ( ) - 1 ; while ( i < j ) { if ( s [ i ] != s [ j ] ) return false ; i ++ ; j -- ; } return true ; } int getIndex ( string S1 , string S2 , int n ) { string S = " " ; for ( int i = 0 ; i < n ; i ++ ) { S = S + S1 [ i ] ; string Temp = " " ; for ( int j = i + 1 ; j < n ; j ++ ) Temp += S2 [ j ] ; if ( isPalindrome ( S + Temp ) ) { return i ; } } return -1 ; } int main ( ) { string S1 = " abcdf " , S2 = " sfgba " ; int n = S1 . length ( ) ; cout << getIndex ( S1 , S2 , n ) ; return 0 ; }