Вот подход, основанный на регулярных выражениях, который, кажется, работает:
input = "ddaaabbbbbbbbccceeeeeee"
n = 3
for match in re.finditer(r'(.)(?!\1)(.)\2{' + str(n-1) + r'}(?!\2)', input):
print(match.group(0)[1:])
aaa
ccc
Шаблон регулярного выражения, используемый в приведенном выше примере, выглядит следующим образом:
(.)(?!\1)(.)\2{2}(?!\2)
Это говорит:
(.) match and capture any single character
(?!\1) assert that the next character is different
(.) then match and capture that next character
\2{2} which is then followed by that same character exactly twice (total of 3)
(?!\2) after three instances, the character that follows is NOT the same