Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define NO_OF_CHARS 256
- #define N 100
- // C function to find the second most frequent character
- // in a given string 'str'
- char getSecondMostFreq(char *str)
- {
- // count number of occurrences of every character.
- int count[NO_OF_CHARS] = {0}, i;
- for (i=0; str[i]; i++)
- (count[str[i]])++;
- // Traverse through the count[] and find second highest element.
- int first = 0, second = 0, third = 0;
- for (i = 0; i < NO_OF_CHARS; i++)
- {
- /* If current element is smaller than first then update both
- first and second */
- if (count[i] > count[first])
- {
- third = second;
- second = first;
- first = i;
- }
- /* If count[i] is in between first and second then update second */
- else if (count[i] > count[second] &&
- count[i] != count[first] &&
- count[i] != count[third])
- second = i;
- }
- return second;
- }
- char getThirdMostFreq(char *str)
- {
- // count number of occurrences of every character.
- int count[NO_OF_CHARS] = {0}, i;
- for (i=0; str[i]; i++)
- (count[str[i]])++;
- // Traverse through the count[] and find second highest element.
- int first = 0, second = 0, third = 0;
- for (i = 0; i < NO_OF_CHARS; i++)
- {
- /* If current element is smaller than first then update both
- first and second */
- if (count[i] > count[first])
- {
- third = second;
- second = first;
- first = i;
- }
- /* If count[i] is in between first and second then update second */
- else if (count[i] != count[second] &&
- count[i] != count[first] &&
- count[i] > count[third])
- third = i;
- }
- return third;
- }
- // Driver program to test above function
- int main()
- {
- char str[N];
- scanf("%s", &str);
- char res = getSecondMostFreq(str);
- if (res != '\0')
- printf("Second most frequent char is %c", res);
- else
- printf("No second most frequent character");
- char str[] = *str
- char res = getThirdMostFreq(str);
- if (res != '\0')
- printf("Third most frequent char is %c", res);
- else
- printf("No third most frequent character");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement