1080. 统计字符
题目描述
Johe最近玩起了字符游戏,规则是这样的:读入四行字符串,其中的字母都是大写的,Johe想打印一个柱状图显示每个大写字母的频率。你能帮助他吗?
输入
输入文件共有4行:每行为一串字符,不超过100个字符。
输出
与样例的格式保持严格一致。
样例输入
THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.
THIS IS AN EXAMPLE TO TEST FOR YOUR
HISTOGRAM PROGRAM.
HELLO!
样例输出
数据范围限制
提示
1.输出的相邻字符间有一个空格。
2.最后一行的26个大写字母每次必须输出。
C++代码
#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <cassert>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
const int max_char_frenquency = 500; // maximum character frequency
char charBarGraph[26][max_char_frenquency]; // 'A' to 'Z'
const int max_lines = 4;
const int max_num_of_chars_per_line = 100;
string strText;
map<char, int> JoheGame;
for(int i=1; i<=max_lines; i++)
{
getline(cin, strText);
for(unsigned int j=0; j<strText.size() && j<max_num_of_chars_per_line; j++)
{
char c = strText[j];
if (c >= 'A' && c <= 'Z')
{
JoheGame[c]++;
}
}
}
for(int i=0; i<26; i++) // from 'A' to 'Z': 26 characters
{
memset(charBarGraph, ' ', sizeof(charBarGraph)); // default is blank (' ')
}
map<char, int>::iterator iter;
int actual_max_char_frequency = 0; // actual maximum char frequency
int index; // char index from 0 to 25
for(iter=JoheGame.begin();iter!=JoheGame.end();iter++)
{
actual_max_char_frequency = max(iter->second, actual_max_char_frequency);
index = int(iter->first - 'A');
charBarGraph[index][0] = iter->first; // first char is 'A'..'Z'
for(int j=1; j<=iter->second; j++)
{
charBarGraph[index][j] = '*'; // fill with '*' according to char frequency
}
}
// output char bar graph after statistics
for(int j=actual_max_char_frequency; j>=0; j--)
{
for(int i=0; i<26; i++)
{
cout << charBarGraph[i][j] << " "; // add one blank between two columns
}
cout << endl;
}
return 0;
}