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