Write an efficient C function to return maximum occurring character in the input string e.g., if input string is “test string” then function should return ‘t’.
Algorithm:
Input string = “test” 1: Construct character count array from the input string. count['e'] = 1 count['s'] = 1 count['t'] = 2 2: Return the index of maximum value in count array (returns ‘t’).
Implementation:
- C++
- Python
// C++ program to output the maximum occurring character in a string #include<bits/stdc++.h> #define ASCII_SIZE 256 using namespace std; char getMaxOccuringChar( char * str) { // Create array to keep the count of individual characters int count[ASCII_SIZE]; // Initialize the count array to zero for ( int j=0; j < ASCII_SIZE; j++) count[j] = 0; // Utility variables int len = strlen (str); int max = -1; char c; // Traversing through the string and maintaining the count of // each character for ( int i = 0; i < len; i++) { if (max < count[str[i]]) { max = count[str[i]]; c = str[i]; } } return c; } // Driver program to test the above function int main() { char * str = "sample string" ; cout << "Max occurring character is " << getMaxOccuringChar(str); } |
Implementation:
Output:
Max occurring character is s
Time Complexity: O(n)
Notes:
If more than one character have the same and maximum count then function returns only the first character in alphabetical order. For example if input string is “test sample” then function will return only ‘e’.
If more than one character have the same and maximum count then function returns only the first character in alphabetical order. For example if input string is “test sample” then function will return only ‘e’.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above