Smallest length string with repeated replacement of two distinct adjacent | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int stringReduction ( string str ) { int n = str . length ( ) ; int count [ 3 ] = { 0 } ; for ( int i = 0 ; i < n ; ++ i ) count [ str [ 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 ; } int main ( ) { string str = " abcbbaacb " ; cout << stringReduction ( str ) ; return 0 ; }