Regular expression solution-balanced string

Source: Internet
Author: User

Requirements:

1. The same number of a or B in a string

2. The difference between A and B in any prefix of a string (substring starting from the head of a string) does not exceed 1

For such a problem, the better way is to write a few cases to find the law.

As required, the beginning is divided into two cases (1) starting with a 2) beginning with B. Both cases are symmetric and solving any one can solve the whole problem.

PS According to the first rule, the whole string must be even.

If starting with a, the second character can only be B (if a is a violation of the second rule)

Ab

The third character can be a or B,

1) If the A:aba

Then the fourth string must be B:abab

2) if the B

Then the fourth string must be A:abba

Did you find anything? We found that the substring in 2 is always the same as AB or BA.

So the question becomes: AB or BA occurrences of the string

The answer is

^ ((AB) | (BA)) *$

Regular expression solution-balanced string

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.