Determine the winner of a game of deleting Characters from a String | Java program for the above approach ; Function to find the winner of the game when both players play optimally ; Stores the frequency of all digit ; Stores the scores of player1 and player2 respectively ; Iterate to store frequencies ; Turn for the player1 ; Add score of player1 ; Add score of player2 ; Check if its a draw ; If score of player 1 is greater ; Otherwise ; Driver code
import java . util . * ; class GFG { static void determineWinner ( String str ) { int [ ] A = new int [ 10 ] ; int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { A [ ( int ) str . charAt ( i ) - 48 ] ++ ; } for ( int i = 0 ; i <= 9 ; i ++ ) { if ( i % 2 != 0 ) { sum1 = sum1 + A [ i ] ; } else { sum2 = sum2 + A [ i ] ; } } if ( sum1 == sum2 ) { System . out . print ( " - 1" ) ; } else if ( sum1 > sum2 ) { System . out . print ( " Player ▁ 1" ) ; } else { System . out . print ( " Player ▁ 2" ) ; } } public static void main ( String [ ] args ) { String str = "78787" ; determineWinner ( str ) ; } }