Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | Java program for 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
import java . io . * ; import java . util . * ; class GFG { static boolean isPalindrome ( String str ) { int i = 0 , j = str . length ( ) - 1 ; while ( i < j ) { if ( str . charAt ( i ) != str . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static void formPalindrome ( String a , String b , int n ) { char aa [ ] = new char [ n + 2 ] ; char bb [ ] = new char [ n + 2 ] ; Arrays . fill ( aa , ' ▁ ' ) ; Arrays . fill ( bb , ' ▁ ' ) ; for ( int i = 1 ; i <= n ; i ++ ) { aa [ i ] = a . charAt ( i - 1 ) ; bb [ i ] = b . charAt ( i - 1 ) ; } boolean ok = false ; for ( int i = 0 ; i <= n + 1 ; i ++ ) { StringBuilder la = new StringBuilder ( ) ; StringBuilder ra = new StringBuilder ( ) ; StringBuilder lb = new StringBuilder ( ) ; StringBuilder rb = new StringBuilder ( ) ; for ( int j = 1 ; j <= i - 1 ; j ++ ) { la . append ( ( aa [ j ] == ' ▁ ' ) ? " " : aa [ j ] ) ; lb . append ( ( bb [ j ] == ' ▁ ' ) ? " " : bb [ j ] ) ; } for ( int j = i ; j <= n + 1 ; j ++ ) { ra . append ( ( aa [ j ] == ' ▁ ' ) ? " " : aa [ j ] ) ; rb . append ( ( bb [ j ] == ' ▁ ' ) ? " " : bb [ j ] ) ; } if ( isPalindrome ( la . toString ( ) + rb . toString ( ) ) || isPalindrome ( lb . toString ( ) + ra . toString ( ) ) ) { ok = true ; break ; } } if ( ok ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { String A = " bdea " ; String B = " abbb " ; int N = 4 ; formPalindrome ( A , B , N ) ; } }