Problem Description:
Given A string consisting of a, B and C ' s, we can perform the following operation:take any and adjacent distinct character s and replace it with the third character. For example, if ' a ' and ' C ' is adjacent, they can replaced with ' B '. What's the smallest string which can result by applying this operation repeatedly?
Translation:
Given a string composed of a/b/c, you can replace the next and different two characters with the remaining one, for example, you can replace ' ab ' in the string with ' C '. What is the minimum length of the last string that can be obtained through constant substitution operations?
Sample Input
3
Cab
Bcab
CCCCC
Sample Output
2
1
5
Sample explanation:
Cab, CC or CAB, BB
Bcab, AAB, ac-B
CCCCC not variable
Answer:
The answer to this question is applauded. It is divided into three situations:
First, if the characters in the string are all the same, the length of the string is returned directly.
Second, if the number of three characters is odd or even, then the answer is 2.
In other cases, return 1.
correctness Proof :(mathematical induction), n denotes the length of a string
First of all, when the n=3. Returns 3 if the characters are the same, or 2 if they are all different, and returns 1 for other cases.
Second, when N>3, if the character in the string is not all the same, we can use the substitution law to obtain a string of length N-1, and the string is not composed of the same character
Another rule is that a string with an odd number of characters is converted into a string with an even number of characters and vice versa.
Analysis of String reduction problem