To solve this problem, we need to find the character that appears consecutively the most times in a given string. If multiple characters have the same maximum consecutive count, we return the first one encountered.
Approach
The approach involves tracking the current consecutive sequence of characters and comparing it with the maximum sequence found so far:
- Initialization: Start with the first character as the current character and set its count to 1. Also, initialize the maximum character and count with these values.
- Iterate through the string: For each subsequent character:
- If it matches the current character, increment the current count.
- If it doesn't, compare the current count with the maximum count. Update the maximum values if the current count is larger (ignore if equal to keep the first occurrence). Reset the current character and count to the new character.
- Final check: After the loop ends, compare the last sequence with the maximum to ensure we don't miss the final consecutive sequence.
Solution Code
def find_max_consecutive_char(s):
if not s:
return None, 0 # Handle empty string case
max_char = s[0]
max_count = 1
current_char = s[0]
current_count = 1
for char in s[1:]:
if char == current_char:
current_count += 1
else:
# Update max if current sequence is longer
if current_count > max_count:
max_count = current_count
max_char = current_char
# Reset for new sequence
current_char = char
current_count = 1
# Check the last sequence
if current_count > max_count:
max_count = current_count
max_char = current_char
return max_char, max_count
Explanation
- Initialization: We start with the first character to avoid edge cases for single-character strings.
- Iteration: For each character, we either extend the current sequence or reset it. This ensures we track consecutive sequences efficiently.
- Final Check: The last sequence isn't processed in the loop, so we need to compare it with the maximum to get the correct result.
This approach runs in O(n) time complexity (n is the length of the string) since we iterate through the string once, making it efficient for large inputs. The space complexity is O(1) as we only use a few variables to track the sequences.
Example Usage:
- Input: "aabbbccddddd" → Output: ('d', 5)
- Input: "aabbcc" → Output: ('a', 2)
- Input: "abba" → Output: ('b', 2)
- Input: "z" → Output: ('z',1)
This solution correctly handles all edge cases and meets the problem requirements.


作者声明:本文包含人工智能生成内容。