Minimum replacements in a string to make adjacent characters unequal | Java 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
import java . util . * ; class GFG { static void count_minimum ( String s ) { int n = s . length ( ) ; int ans = 0 ; int i = 0 ; while ( i < n ) { int j = i ; while ( j < n && s . charAt ( j ) == s . charAt ( i ) ) { j ++ ; } int diff = j - i ; ans += diff / 2 ; i = j ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String str = " caaab " ; count_minimum ( str ) ; } }