C程序:如何查找字符串中字符的最大/最小频率 [英] C program: how to find the maximum/minimum frequency of a character in a string
问题描述
我正在尝试找到一种方法来获取字符串中字符的最大/最小频率值
I am trying to find a way to get the values of max/min freq of characters in a string
例如helpme
将具有max freq = 2和min freq = 1
(有2个e,并且其他字母一次出现)
would have max freq = 2 and min freq = 1 (there are 2 e's and there are other letters that occurs once)
另一个aaaa
将具有最大频率= 4和最小频率= 4
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.
此外,相对于包含类型转换和诸如此类的优雅解决方案,我更喜欢蛮力搜索。刚开始使用C,请尽可能简单。顺便说一句,我不在乎这只是建议还是基本操作方法。我不一定需要完整的代码。
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.
预先感谢
推荐答案
您需要构建直方图:
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.
这篇关于C程序:如何查找字符串中字符的最大/最小频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!