
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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