You need to identify disjunct sets of characters. A disjunct set of characters is a set of characters that will all have to become the same character in order for the string to become a palindrome.
Example:
Let's say we have the string abcdefgfmdebac
It has 3 disjunct sets, abc
, de
and fgm
Algorithm:
Pick the first character and check all occurences of it picking up other characters in the set. In the example string we start with
a
and pick upb
andc
(because they sit on the opposite sides of the twoa
in our string). We repeat the process forb
andc
, but no new characters are added to the set. Soabc
is our first disjunct set. Continue doing this with the remaining characters.A disjunct set of
n
characters (counting all characters) needsn-m
replacements, where m is the number of occurences of the most frequent character. So simply sum over the sets.
In our example it takes 4 + 2 + 2 = 8 replacements.