Lexicographically largest string possible by repeatedly appending first character of two given strings | C ++ 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 word2 ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string largestMerge ( string word1 , string word2 ) { string merge = " " ; while ( word1 . size ( ) != 0 || word2 . size ( ) != 0 ) { if ( word1 >= word2 ) { merge = merge + word1 [ 0 ] ; word1 . erase ( word1 . begin ( ) + 0 ) ; } else { merge = merge + word2 [ 0 ] ; word2 . erase ( word2 . begin ( ) + 0 ) ; } } return merge ; } int main ( ) { string S1 = " xyzxyz " ; string S2 = " xywzxyx " ; cout << largestMerge ( S1 , S2 ) ; return 0 ; }