Lexicographically largest possible by merging two strings by adding one character at a time | Java program for the approach ; Recursive bfunction for finding the lexicographically largest string ; If either of the string length is 0 , return the other string ; If s1 is lexicographically larger than s2 ; Take first character of s1 and call the function ; Take first character of s2 and recursively call function for remaining string ; Given Input ; Function Call
public class Main { static String largestMerge ( String s1 , String s2 ) { if ( s1 . length ( ) == 0 || s2 . length ( ) == 0 ) return s1 + s2 ; if ( s1 . compareTo ( s2 ) > 0 ) { return s1 . charAt ( 0 ) + largestMerge ( s1 . substring ( 1 ) , s2 ) ; } return s2 . charAt ( 0 ) + largestMerge ( s1 , s2 . substring ( 1 ) ) ; } public static void main ( String [ ] args ) { String s1 = " geeks " ; String s2 = " forgeeks " ; System . out . print ( largestMerge ( s1 , s2 ) ) ; } }