Minimum replacements to make adjacent characters unequal in a ternary string | 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 ; Last pair ; Check for character which is not same in i - 1 index ; Driver Code
def countMinimalReplacements ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE cnt = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE if ( i != ( n - 1 ) ) : NEW_LINE INDENT s = list ( s ) NEW_LINE for j in "012" : NEW_LINE INDENT if ( j != s [ i + 1 ] and j != s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = j NEW_LINE break NEW_LINE DEDENT DEDENT s = ' ' . join ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT s = list ( s ) NEW_LINE for k in "012" : NEW_LINE INDENT if ( k != s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = k NEW_LINE break NEW_LINE DEDENT DEDENT s = ' ' . join ( s ) NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "201220211" NEW_LINE print ( countMinimalReplacements ( s ) ) NEW_LINE DEDENT