Minimum moves to make count of lowercase and uppercase letters equal | Java program for the above approach ; Function to calculate minimum number of moves required to convert the string ; Stores Count of upper and lower case characters ; Traverse the string S ; If current character is uppercase ; Increment count of Uppercase characters ; Otherwise , ; Increment count of Lowercase characters ; Stores minimum number of moves needed ; If there are more upper case characters ; Iterate until upper is greater than N / 2 ; Convert uppercase into lowercase until upper = N / 2 ; Increment the pointer ; If there are more lower case characters ; Iterate until lower is greater than N / 2 ; Convert lowercase into uppercase until lower = N / 2 ; Increment the pointer ; Print moves required ; Print resultant string ; Driver code ; Given string ; Function call
class GFG { static void minimumTimeToConvertString ( String S , int N ) { int upper = 0 , lower = 0 ; for ( int i = 0 ; i < N ; i ++ ) { char c = S . charAt ( i ) ; if ( Character . isUpperCase ( c ) ) { upper ++ ; } else { lower ++ ; } } int moves = 0 ; if ( upper > N / 2 ) { int i = 0 ; while ( upper > N / 2 && i < N ) { if ( Character . isUpperCase ( S . charAt ( i ) ) ) { S = S . substring ( 0 , i ) + ( char ) ( S . charAt ( i ) + 32 ) + S . substring ( i + 1 ) ; moves ++ ; upper -- ; lower ++ ; } i ++ ; } } else if ( lower > N / 2 ) { int i = 0 ; while ( lower > N / 2 && i < N ) { if ( Character . isLowerCase ( S . charAt ( i ) ) ) { S = S . substring ( 0 , i ) + ( char ) ( S . charAt ( i ) - 32 ) + S . substring ( i + 1 ) ; moves ++ ; upper ++ ; lower -- ; } i ++ ; } } System . out . println ( moves ) ; System . out . println ( S ) ; } public static void main ( String [ ] args ) { String S = " AbcdEf " ; int N = S . length ( ) ; minimumTimeToConvertString ( S , N ) ; } }