问题
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