Problem
Given a string s
, the task is to find the character that has the maximum number of consecutive repeating occurrences in the string.
Examples
Example 1:
Input: "aaabbbaaaccc"
Output: "a"
Explanation: The character 'a' has the maximum consecutive repeats (three times) at the beginning of the substring "aaa".
Example 2:
Input: "abcd"
Output: "a"
Explanation: Each character repeats only once, so the first character 'a' is the result.
Solution
Method 1 - Using the count
To solve this problem, we can iterate through the string and keep track of the current character and its consecutive count. Whenever we encounter a different character, we compare the current count to the maximum count and update if necessary. We continue this process until we have checked all characters in the string.
Here are the steps:
- Initialize variables to keep track of the maximum consecutive repeating character and its count.
- Use a loop to iterate through the string.
- For each character:
- If it matches the previous character, increment the current count.
- If it does not match, update the maximum count and character if needed, then reset the current count.
- After the loop, ensure to update the maximum count and character one last time in case the string ends with the highest repeating character.
- Return the character with the maximum consecutive repeats.
Code
Java
public class Solution {
public char findMaxConsecutiveChar(String s) {
if (s == null || s.length() == 0) {
throw new IllegalArgumentException("String should not be empty");
}
char maxChar = s.charAt(0);
int maxCount = 1;
int currentCount = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
currentCount++;
} else {
if (currentCount > maxCount) {
maxCount = currentCount;
maxChar = s.charAt(i - 1);
}
currentCount = 1;
}
}
if (currentCount > maxCount) {
maxCount = currentCount;
maxChar = s.charAt(s.length() - 1);
}
return maxChar;
}
}
Python
class Solution:
def findMaxConsecutiveChar(self, s: str) -> str:
if not s:
raise ValueError("String should not be empty")
max_char = s[0]
max_count = 1
current_count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
current_count += 1
else:
if current_count > max_count:
max_count = current_count
max_char = s[i - 1]
current_count = 1
if current_count > max_count:
max_count = current_count
max_char = s[-1]
return max_char
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the string, as we iterate through the string once. - 🧺 Space complexity:
O(n)
, since we use a constant amount of extra space for storing variables.