# Maximum consecutive repeating character in string in C++

We are given a string of alphabets. The task is to find the character which has the longest consecutive repetitions occurring in string. Let’s understand with examples.

Input− String[] = “abbbabbbbcdd”

Output − b

Explanation − In the above string, the longest consecutive sequence is of character ‘b’. Count of consecutive b’s is 4.

Input− String[] = “aabbcdeeeeed”

Output − b

Explanation − In the above string, the longest consecutive sequence is of character ‘e’. Count of consecutive e’s is 5.

## Approach used in the below program is as follows

• The character array string1[] is used to store the string of alphabets.

• Function maxRepeating(char str[], int n) takes two input parameters. The string itself, its size. Returns the character with the longest consecutive repetitions sequence.

• Traverse the string in str[] from 1st position till last.

• If str[i] and next one str[i+1] are the same, increment count .

• If that count is maximum, store the value in maxC and character in repchar.

• Return the repchar as a final result.

## Example

Live Demo

#include <iostream>
#include <iostream>
char maxRepeating(char str[], int n){
int count = 0;
char repchar = str[0];
int maxC = 1;
for (int i=0; i<n; i++){
if (str[i] == str[i+1] && i < n-1 )
maxC++;
else{
if (maxC > count){
count = maxC;
repchar = str[i];
}
maxC = 1;
}
}
return repchar;
}
int main(){
char string1[] = "aaabbaacccddef";
int N=14;
printf("Maximum Consecutive repeating character in string: %c",maxRepeating(string1,N));
return 0;
}

## Output

If we run the above code it will generate the following output −

Maximum Consecutive repeating character in string: a

Updated on: 17-Aug-2020

2K+ Views