Minimum replacements to make adjacent characters unequal in a ternary string | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinimalReplacements ( string 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 ( auto it : "012" ) { if ( it != s [ i + 1 ] && it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } { for ( auto it : "012" ) { if ( it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } } } return cnt ; } int main ( ) { string s = "201220211" ; cout << countMinimalReplacements ( s ) ; return 0 ; }