Longest run of a repeated character
Write a Python program to find the character that repeats most times in a row (consecutively) in a string.
"aabbbbcccdd"
b 4
Approach
- Walk through the string, counting the current run, and remember the longest one.
Solution
text = "aabbbbcccdd"best_char, best_len = text[0], 1run_len = 1for i in range(1, len(text)): if text[i] == text[i - 1]: run_len += 1 else: run_len = 1 if run_len > best_len: best_char, best_len = text[i], run_lenprint(best_char, best_len)b 4
Line by line
The run grows while characters repeat and resets on a change.
Save the run if it is the longest so far.
itertools.groupby(text) groups consecutive equal characters for you.
Learn the concept
New to this topic? Read the lesson, then come back.