Minimum replacements to make adjacent characters unequal in a ternary string | Java program to count the minimal replacements such that adjacent characters are unequal ; Function to count the number of minimal replacements ; Find the length of the String ; Iterate in the String ; Check if adjacent is similar ; If not the last pair ; Check for character which is not same in i + 1 and i - 1 ; else Last pair ; Check for character which is not same in i - 1 index ; Driver Code
class GFG { static final int MAX = 26 ; static int countMinimalReplacements ( char [ ] s ) { int n = s . length ; int cnt = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { cnt += 1 ; if ( i != ( n - 1 ) ) { for ( char it : "012" . toCharArray ( ) ) { if ( it != s [ i + 1 ] && it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } { for ( char it : "012" . toCharArray ( ) ) { if ( it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } } } return cnt ; } public static void main ( String [ ] args ) { String s = "201220211" ; System . out . println ( countMinimalReplacements ( s . toCharArray ( ) ) ) ; } }