我希望打印出来" getMostFreqLetter(s)
的返回值为letter' e',其频率为11。"但是这个函数只能返回char类型的问题,我被困在这里,需要一些帮助
char getMostFreqLetter (string s){
int maxNum = 0; // the max frequency of occurring of letters
char maxChar = ' '; // the max occurring of letters
/* count the uppercase letters */
for (char i = 65; i <= 90; i++){ // from A to z based on ascii table value
int count = 0; // count the frequency of occurring of letters which compare with maxMun
for(int j = 0; j < s.length(); j++){
if(s[j] == i){
count ++;
}
/* compare current frequency letters and existing most frequency letters */
if(count > maxNum){ // display the first alphabet letter if there are multiple same frequency letters occurring
maxNum = count;
maxChar = i;
}
}
}
/* count the lowercase letters */
for (char i = 97; i <= 122; i++){ // From a to z based on ascii table value
int count = 0; // Count the frequency of occurring of letters which compare with maxMun
for(int j = 0; j < s.length(); j++){
if(s[j] == i){
count ++;
}
/* Compare current frequency letters and existing most frequency letters */
if(count > maxNum){ // display the first alphabet letter if there are multiple same frequency letters occurring
maxNum = count;
maxChar = i;
}
}
}
//cout << "getMostFreqLetter(s) output: letter '" << maxChar <<"', whose frequency is " << maxNum << "." << endl;
return maxChar ;
}
顺便说一句,有没有简单的方法将2个大写和小写的循环组合成一个循环?
答案 0 :(得分:2)
对函数的最小更改是将其声明为:
std::pair<char,int> getMostFreqLetter (std::string s){
并将return语句设为:
return {maxChar, maxNum};
用法是:
const auto freq = getMostFreqLetter(s);
std::cout << "Most frequent letter is " << freq.first
<< " whose frequency is " << freq.second << std::endl;
最好使用适当类型的元素freq_t
和letter
来定义结构frequency
。
为了加快速度,我会使用一个大小为CHAR_MAX的数组,并执行以下操作:
for (const char ch: s)
freq[(unsigned)ch]++;
强制转换是因为char
可能会被签名,如果你有一个设置了最高位的字符,你就会对数组的前面进行索引。
然后你必须找到最高元素(而字符是索引)。
您可以将数组概念扩展为Unicode(这也可以避免强制转换)将std::map<unicode_char,int>
用于unicode_char
的合适选择。