Short Problem Definition:
Consider a string, s, consisting only of the letters a
and b
. We say that string s is balanced if both of the following conditions are satisfied:
- s has the same number of occurrences of
a
andb
. - In each prefix of s, the number of occurrences of
a
andb
differ by at most 1.
Your task is to write a regular expression accepting only balanced strings.
Link
Execution:
Substrings can differ by at most 1 which means that the string must consist of either “ab” or “ba”. Write a regex as such.
Solution:
Regex_Pattern = r"^((ab)|(ba))*$" # Do not delete 'r'.