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 ; else Last pair ; Check for character which is not same in i - 1 index ; Driver Code
< ? php function countMinimalReplacements ( $ s ) { $ n = strlen ( $ s ) ; $ cnt = 0 ; $ str = "012" ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( $ s [ $ i ] == $ s [ $ i - 1 ] ) { $ cnt += 1 ; if ( $ i != ( $ n - 1 ) ) { for ( $ it = 0 ; $ it < strlen ( $ str ) ; $ it ++ ) { if ( $ str [ $ it ] != $ s [ $ i + 1 ] && $ str [ $ it ] != $ s [ $ i - 1 ] ) { $ s [ $ i ] = $ str [ $ it ] ; break ; } } } { for ( $ it = 0 ; $ it < strlen ( $ str ) ; $ it ++ ) { if ( $ str [ $ it ] != $ s [ $ i - 1 ] ) { $ s [ $ i ] = $ str [ $ it ] ; break ; } } } } } return $ cnt ; } $ s = "201220211" ; echo countMinimalReplacements ( $ s ) ; ? >