Longest palindromic string possible by concatenating strings from a given array | C ++ program for the above approach ; Stores the distinct strings from the given array ; Insert the strings into set ; Stores the left and right substrings of the given string ; Stores the middle substring ; Traverse the array of strings ; Reverse the current string ; Checking if the string is itself a palindrome or not ; Check if the reverse of the string is present or not ; Append to the left substring ; Append to the right substring ; Erase both the strings from the set ; Print the left substring ; Print the middle substring ; Print the right substring ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void max_len ( string s [ ] , int N , int M ) { unordered_set < string > set_str ; for ( int i = 0 ; i < N ; i ++ ) { set_str . insert ( s [ i ] ) ; } vector < string > left_ans , right_ans ; string mid ; for ( int i = 0 ; i < N ; i ++ ) { string t = s [ i ] ; reverse ( t . begin ( ) , t . end ( ) ) ; if ( t == s [ i ] ) { mid = t ; } else if ( set_str . find ( t ) != set_str . end ( ) ) { left_ans . push_back ( s [ i ] ) ; right_ans . push_back ( t ) ; set_str . erase ( s [ i ] ) ; set_str . erase ( t ) ; } } for ( auto x : left_ans ) { cout << x ; } cout << mid ; reverse ( right_ans . begin ( ) , right_ans . end ( ) ) ; for ( auto x : right_ans ) { cout << x ; } } int main ( ) { int N = 4 , M = 3 ; string s [ ] = { " omg " , " bbb " , " ffd " , " gmo " } ; max_len ( s , N , M ) ; return 0 ; }