Lexicographically largest string possible by repeatedly appending first character of two given strings | Java program for the above approach ; Function to make the lexicographically largest string by merging two strings ; Stores the resultant string ; If the string word1 is lexographically greater than or equal to word ; Update the string merge ; Erase the first index of the string word1 ; Otherwise ; Update the string merge ; Erase the first index of the string word2 ; Return the final string ; Driver Code
import java . io . * ; class GFG { static String largestMerge ( String word1 , String word2 ) { String merge = " " ; while ( word1 . length ( ) != 0 || word2 . length ( ) != 0 ) { if ( word1 . compareTo ( word2 ) == 0 || ( word1 . compareTo ( word2 ) > 0 ) ) { merge = merge + word1 . charAt ( 0 ) ; word1 = word1 . substring ( 1 ) ; } else { merge = merge + word2 . charAt ( 0 ) ; word2 = word2 . substring ( 1 ) ; } } return merge ; } public static void main ( String [ ] args ) { String S1 = " xyzxyz " ; String S2 = " xywzxyx " ; System . out . println ( largestMerge ( S1 , S2 ) ) ; } }