Longest palindromic string possible by concatenating strings from a given array | Java 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
import java . util . * ; class GFG { static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } static void max_len ( String s [ ] , int N , int M ) { HashSet < String > set_str = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { set_str . add ( s [ i ] ) ; } Vector < String > left_ans = new Vector < > ( ) ; Vector < String > right_ans = new Vector < > ( ) ; String mid = " " ; for ( int i = 0 ; i < N ; i ++ ) { String t = s [ i ] ; t = reverse ( t ) ; if ( t == s [ i ] ) { mid = t ; } else if ( set_str . contains ( t ) ) { left_ans . add ( s [ i ] ) ; right_ans . add ( t ) ; set_str . remove ( s [ i ] ) ; set_str . remove ( t ) ; } } for ( String x : left_ans ) { System . out . print ( x ) ; } System . out . print ( mid ) ; Collections . reverse ( right_ans ) ; for ( String x : right_ans ) { System . out . print ( x ) ; } } public static void main ( String [ ] args ) { int N = 4 , M = 3 ; String s [ ] = { " omg " , " bbb " , " ffd " , " gmo " } ; max_len ( s , N , M ) ; } }