Minimum replacements in a string to make adjacent characters unequal | C ++ program to find minimum replacements in a string to make adjacent characters unequal ; Function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; Move j until characters s [ i ] & s [ j ] are equal or the end of the string is reached ; diff stores the length of the substring such that all the characters are equal in it ; We need atleast diff / 2 operations for this substring ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void count_minimum ( string s ) { int n = s . length ( ) ; int ans = 0 ; int i = 0 ; while ( i < n ) { int j = i ; while ( s [ j ] == s [ i ] && j < n ) { j ++ ; } int diff = j - i ; ans += diff / 2 ; i = j ; } cout << ans << endl ; } int main ( ) { string str = " caaab " ; count_minimum ( str ) ; return 0 ; }