Smallest length string with repeated replacement of two distinct adjacent | Java program to find smallest possible length of a string of only three characters ; Returns smallest possible length with given operation allowed . ; Counint occurrences of three different characters ' a ' , ' b ' and ' c ' in str ; If all characters are same . ; If all characters are present even number of times or all are present odd number of times . ; Answer is 1 for all other cases . ; Driver code
public class GFG { static int stringReduction ( String str ) { int n = str . length ( ) ; int count [ ] = new int [ 3 ] ; for ( int i = 0 ; i < n ; ++ i ) { count [ str . charAt ( i ) - ' a ' ] ++ ; } if ( count [ 0 ] == n count [ 1 ] == n count [ 2 ] == n ) { return n ; } if ( ( count [ 0 ] % 2 ) == ( count [ 1 ] % 2 ) && ( count [ 1 ] % 2 ) == ( count [ 2 ] % 2 ) ) { return 2 ; } return 1 ; } public static void main ( String [ ] args ) { String str = " abcbbaacb " ; System . out . println ( stringReduction ( str ) ) ; } }