UVa 11577 – Letter Frequency
We are interested in a question: What is the most frequently appearing letter in this line of text?
We can ignore some non-alphabetic characters. However, it's important to note that if both uppercase 'A' and lowercase 'a' appear, they both count as 'a'.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The first line represents how many test cases there are. Each line is one test case. This line may contain spaces, but at least one letter. The total number of letters in each line does not exceed 200. | For each test case, output the most frequent lowercase letter. (If there are ties, output the one that comes first alphabetically.) |
1 Computers account for only 5% of the country’s commercial electricity consumption. | co |
Thought Process
First, store the frequency of each letter in a map. Then, iterate through this map using auto, and initialize a new map (with keys as integers and values as vectors).
Multiply the values from the old map by -1 and use them as keys for the new map. Push the characters back into the value vector of the new map.
Afterward, iterate through the new map using auto. First, sort the vector inside and output the letters. Then, you can break out of this loop because you only need to output the letter(s) with the highest frequency.
Sample Code-ZeroJudge D267: Letter Frequency
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
string a;
getline(cin, a);
for (int i = 0; i<N; i++)
{
string str;
getline(cin, str);
map<char, int>MAP;
for (int j = 0; j<str.length(); j++)
{
if (isalpha(str[j]))
{
MAP[tolower(str[j])]++;
}
}
map<int, vector<char>>ans;
for (auto it:MAP)
{
ans[it.second * -1].push_back(it.first);
}
for (auto it:ans)
{
sort(it.second.begin(), it.second.end());
for (int j = 0; j<it.second.size(); j++)
{
cout << it.second[j];
}
cout << "\n";
break;
}
}
}
//ZeroJudge D267
//Dr. SeanXD