Minimize swaps of same | Java program for the above approach ; Function to count the number of swaps required to make the sum of ASCII values of the characters of both strings odd ; Initialize alphabets with value ; Initialize values for each alphabet ; Size of the string ; Sum of string S ; Sum of string T ; Stores whether there is any index i such that S [ i ] and T [ i ] have different parities ; Traverse the strings ; Update sum1 and sum2 ; If S [ i ] and T [ i ] have different parities ; If sum1 and sum2 are both odd ; If sum1 and sum2 are both even ; If exists print 1 ; Otherwise ; If sum1 and sum2 are of different parities ; Driver Code ; Function Call
import java . io . * ; class GFG { static void countSwaps ( String S , String T ) { int [ ] value = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) value [ i ] = i + 1 ; int N = S . length ( ) ; int sum1 = 0 ; int sum2 = 0 ; boolean flag = false ; for ( int i = 0 ; i < N ; i ++ ) { sum1 += value [ S . charAt ( i ) - ' a ' ] ; sum2 += value [ T . charAt ( i ) - ' a ' ] ; if ( ( value [ S . charAt ( i ) - ' a ' ] % 2 == 0 && value [ T . charAt ( i ) - ' a ' ] % 2 == 1 ) || ( value [ S . charAt ( i ) - ' a ' ] % 2 == 1 && value [ T . charAt ( i ) - ' a ' ] % 2 == 0 ) ) flag = false ; } if ( sum1 % 2 == 1 && sum2 % 2 == 1 ) System . out . println ( "0NEW_LINE"); else if ( sum1 % 2 == 0 && sum2 % 2 == 0 ) { if ( flag ) System . out . println ( "1" ) ; else System . out . println ( " - 1" ) ; } else { System . out . println ( " - 1" ) ; } } public static void main ( String [ ] args ) { String S = " acd " ; String T = " dbf " ; countSwaps ( S , T ) ; } }