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
function countMinimalReplacements ( s ) { var n = s . length ; var cnt = 0 ; var str = " " ; for ( var i = 1 ; i < n ; i ++ ) { if ( s [ i ] === s [ i - 1 ] ) { cnt += 1 ; if ( i !== n - 1 ) { for ( var it = 0 ; it < str . length ; it ++ ) { if ( str [ it ] !== s [ i + 1 ] && str [ it ] !== s [ i - 1 ] ) { s [ i ] = str [ it ] ; break ; } } else { for ( var it = 0 ; it < str . length ; it ++ ) { if ( str [ it ] !== s [ i - 1 ] ) { s [ i ] = str [ it ] ; break ; } } } } } return cnt ; } var s = " " ; document . write ( countMinimalReplacements ( s ) ) ;