Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | C ++ Program to implement the above approach ; Function to check if a string is palindrome or not ; Start and end of the string ; Iterate the string until i > j ; If there is a mismatch ; Increment first pointer and decrement the other ; Given string is a palindrome ; Function two check if the strings can be combined to form a palindrome ; Initialize array of characters ; Stores character of string in the character array ; Find left and right parts of strings a and b ; Substring a [ j ... i - 1 ] ; Substring b [ j ... i - 1 ] ; Substring a [ i ... n ] ; Substring b [ i ... n ] ; Check is left part of a + right part of b or vice versa is a palindrome ; Print the result ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int i = 0 , j = str . size ( ) - 1 ; while ( i < j ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; j -- ; } return true ; } void formPalindrome ( string a , string b , int n ) { char aa [ n + 2 ] ; char bb [ n + 2 ] ; for ( int i = 0 ; i < n + 2 ; i ++ ) { aa [ i ] = ' ▁ ' ; bb [ i ] = ' ▁ ' ; } for ( int i = 1 ; i <= n ; i ++ ) { aa [ i ] = a [ i - 1 ] ; bb [ i ] = b [ i - 1 ] ; } bool ok = false ; for ( int i = 0 ; i <= n + 1 ; i ++ ) { string la = " " ; string ra = " " ; string lb = " " ; string rb = " " ; for ( int j = 1 ; j <= i - 1 ; j ++ ) { if ( aa [ j ] == ' ▁ ' ) la += " " ; else la += aa [ j ] ; if ( bb [ j ] == ' ▁ ' ) lb += " " ; else lb += bb [ j ] ; } for ( int j = i ; j <= n + 1 ; j ++ ) { if ( aa [ j ] == ' ▁ ' ) ra += " " ; else ra += aa [ j ] ; if ( bb [ j ] == ' ▁ ' ) rb += " " ; else rb += bb [ j ] ; } if ( isPalindrome ( la + rb ) || isPalindrome ( lb + ra ) ) { ok = true ; break ; } } if ( ok ) cout << ( " Yes " ) ; else cout << ( " No " ) ; } int main ( ) { string A = " bdea " ; string B = " abbb " ; int N = 4 ; formPalindrome ( A , B , N ) ; }