Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | C ++ program to implement the above approach ; Function that returns true if the sub - string starting from index i and ending at index j is a palindrome ; Function to get the required index ; Start comparing the two strings from both ends . ; Break from the loop at first mismatch ; If it is possible to concatenate the strings to form palindrome , return index ; If remaining part for s2 is palindrome ; If remaining part for s1 is palindrome ; If not possible , return - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string s , int i , int j ) { while ( i < j ) { if ( s [ i ] != s [ j ] ) return false ; i ++ ; j -- ; } return true ; } int getIndex ( string s1 , string s2 , int len ) { int i = 0 , j = len - 1 ; while ( i < j ) { if ( s1 [ i ] != s2 [ j ] ) { break ; } i ++ ; j -- ; } if ( i == j ) { return i - 1 ; } else if ( isPalindrome ( s2 , i , j ) ) return i - 1 ; else if ( isPalindrome ( s1 , i , j ) ) return j ; return -1 ; } int main ( ) { string s1 = " abcdf " , s2 = " sfgba " ; int len = s1 . length ( ) ; cout << getIndex ( s1 , s2 , len ) ; return 0 ; }