C program: how to find the maximum/minimum frequency of a character in a string

痞子三分冷 提交于 2019-12-20 03:50:34

问题


I am trying to find a way to get the values of max/min freq of characters in a string

E.g. helpme

would have max freq = 2 and min freq = 1 (there are 2 e's and there are other letters that occurs once)

another E.g. aaaa

would have max freq = 4 and min freq = 4

I am trying to program this, but I don't know what to do after I receive the string by using scanf.

Assume that there are only lowercase and there are no space between words.

Additionally, I prefer more of a brute force search over an elegant solution that consists of type casting and whatnot. Just started to use C, so simple as possible please. BTW, I don't mind if it's just an advice or a basic procedure of how to do this. I don't necessarily need the whole code.

Thanks in advance


回答1:


You need to build a histogram:

size_t histogram[UCHAR_MAX] = { 0 };     // allocate and initialise histogram

for (size_t i = 0; s[i] != '\0'; ++i)    // generate histogram for string s
{
    histogram[(unsigned int)s[i]]++;
}

After this you can just do a linear scan through the histogram looking for the min and max letter frequencies.



来源:https://stackoverflow.com/questions/14563853/c-program-how-to-find-the-maximum-minimum-frequency-of-a-character-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!