在本教程中,我们将讨论一个查找第二个最常见字符的程序。
为此,我们将提供一个字符串。我们的任务是仅将字符串迭代一次,然后在其中查找第二个最常见的字符。
#include <bits/stdc++.h> using namespace std; #define NO_OF_CHARS 256 //找到第二个最常出现的角色 char getSecondMostFreq(string str) { int count[NO_OF_CHARS] = {0}, i; for (i = 0; str[i]; i++) (count[str[i]])++; int first = 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++){ if (count[i] > count[first]){ second = first; first = i; } else if (count[i] > count[second] && count[i] != count[first]) second = i; } return second; } int main(){ string str = "nhooo"; char res = getSecondMostFreq(str); if (res != '\0') cout << "Second most frequent char is " << res; else cout << "No second most frequent character"; return 0; }
输出结果
Second most frequent char is i