Middle — Senior
Write a function that returns the character with the maximum number of consecutive repetitions in a string.
sobes.tech AI
Answer from AI
python def max_consecutive_char(s: str) -> str: if not s: return ''
max_char = s[0]
max_count = 1
current_char = s[0]
current_count = 1
for i in range(1, len(s)):
if s[i] == current_char:
current_count += 1
else:
if current_count > max_count:
max_count = current_count
max_char = current_char
current_char = s[i]
current_count = 1
# Check for the last sequence of characters
if current_count > max_count:
max_count = current_count
max_char = current_char
return max_char
Example usage
print(max_consecutive_char('aabbbccddddde')) # Will output 'd'
The function iterates through the string once, tracking the current character and the length of its sequence. When the sequence is interrupted, it compares the length with the maximum and updates the result if necessary. At the end, it returns the character with the maximum consecutive repetitions.