Longest palindromic String formed using concatenation of given strings in any order | C ++ implementation to find the longest palindromic String formed using concatenation of given strings in any order ; Function to find the longest palindromic from given array of strings ; Loop to find the pair of strings which are reverse of each other ; Loop to find if any palindromic string is still left in the array ; Update the answer with all strings of pair1 ; Update the answer with palindromic string s1 ; Update the answer with all strings of pair2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void longestPalindrome ( string a [ ] , int n ) { string pair1 [ n ] ; string pair2 [ n ] ; int r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { string s = a [ i ] ; reverse ( s . begin ( ) , s . end ( ) ) ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( a [ i ] != " " && a [ j ] != " " ) { if ( s == a [ j ] ) { pair1 [ r ] = a [ i ] ; pair2 [ r ++ ] = a [ j ] ; a [ i ] = " " ; a [ j ] = " " ; break ; } } } } string s1 = " " ; for ( int i = 0 ; i < n ; i ++ ) { string s = a [ i ] ; reverse ( a [ i ] . begin ( ) , a [ i ] . end ( ) ) ; if ( a [ i ] != " " ) { if ( a [ i ] == s ) { s1 = a [ i ] ; break ; } } } string ans = " " ; for ( int i = 0 ; i < r ; i ++ ) { ans = ans + pair1 [ i ] ; } if ( s1 != " " ) { ans = ans + s1 ; } for ( int j = r - 1 ; j >= 0 ; j -- ) { ans = ans + pair2 [ j ] ; } cout << ans << endl ; } int main ( ) { string a1 [ 2 ] = { " aba " , " aba " } ; int n1 = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; longestPalindrome ( a1 , n1 ) ; string a2 [ 5 ] = { " abc " , " dba " , " kop " , " abd " , " cba " } ; int n2 = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; longestPalindrome ( a2 , n2 ) ; }