问题描述:
Given a string consisting of a,b and c's, we can perform the following operation: Take any two adjacent distinct characters and replace it with the third character. For example, if 'a' and 'c' are adjacent, they can replaced with 'b'. What is the smallest string which can result by applying this operation repeatedly?
For example, you can either get cab -> cc or cab -> bb, resulting in a string of length 2.
For the second case, one optimal solution is: bcab -> aab -> ac -> b. No more operations can be applied and the resultant string has length 1.
翻译:
字符串中任意两个相邻的不同字符都可以替换为第三种字符,问你一个字符串被多次替换后可以剩下的最短长度为多少.
解答:
分为三种情况:
1. 如果字符串中字符全部一样,那么直接返回该字符串的长度即可.
2. 如果三种字符的个数都是奇数或者都是偶数,那么答案为2
3. 其他情况,返回1.
正确性证明:
(数学归纳法),N表示字符串的长度
首先,N=3的时候.如果字符都相同,返回3;如果都不同返回2,其他情况返回1.
其次,当N>3的时候,如果字符串中字符不是全部相同的话,我们可以利用替换法则获得长度为N-1的串,且该串也不是由相同字符组成的
还有一个规律,那就是字符个数全为奇数的串经过转换就变成字符个数全为偶数的串,反之亦然。
http://www.cnblogs.com/xubenben/archive/2013/11/02/3403829.htm