Longest run of a repeated character

MediumString Programs · 8 of 106

Write a Python program to find the character that repeats most times in a row (consecutively) in a string.

Advertisement
Input
"aabbbbcccdd"
Output
b 4

Approach

  1. Walk through the string, counting the current run, and remember the longest one.

Solution

Python
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)
Output
b 4

Line by line

Lines 5-8

The run grows while characters repeat and resets on a change.

Lines 9-10

Save the run if it is the longest so far.

Tip

itertools.groupby(text) groups consecutive equal characters for you.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Leave a Comment