Analysis of String reduction problem

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.