Find the winner of the game | Java implementation of the approach ; Function to find the winner of the game ; To store the strings for both the players ; If the index is even ; Append the current character to player A 's string ; If the index is odd ; Append the current character to player B 's string ; Sort both the strings to get the lexicographically smallest string possible ; Copmpare both the strings to find the winner of the game ; Driver code
import java . util . Arrays ; class GFG { static void find_winner ( String str , int n ) { String str1 = " " , str2 = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { str1 += str . charAt ( i ) ; } else { str2 += str . charAt ( i ) ; } } char a [ ] = str1 . toCharArray ( ) ; Arrays . sort ( a ) ; char b [ ] = str2 . toCharArray ( ) ; Arrays . sort ( b ) ; str1 = new String ( a ) ; str2 = new String ( b ) ; if ( str1 . compareTo ( str2 ) < 0 ) System . out . print ( " A " ) ; else if ( str1 . compareTo ( str2 ) > 0 ) System . out . print ( " B " ) ; else System . out . print ( " Tie " ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; find_winner ( str , n ) ; } }