题目地址:
https://www.luogu.com.cn/problem/P1598
题目描述:
写一个程序从输入文件中去读取四行大写字母(全都是大写的,每行不超过
100
100
100个字符),然后用柱状图输出每个字符在输入文件中出现的次数。严格地按照输出样例来安排你的输出格式。
输入格式:
四行字符,由大写字母组成,每行不超过
100
100
100个字符。
输出格式:
由若干行组成,前几行由空格和星号组成,最后一行则是由空格和字母组成的。在任何一行末尾不要打印不需要的多余空格。不要打印任何空行。
代码如下:
#include <iostream>
using namespace std;
int cnt[26];
string s;
int main() {
for (int i = 0; i < 4; i++) {
getline(cin, s);
for (char ch : s)
if ('A' <= ch && ch <= 'Z')
cnt[ch - 'A']++;
}
int M = 0;
for (int i = 0; i < 26; i++) M = max(M, cnt[i]);
for (int i = M; i; i--) {
s.clear();
for (int x : cnt) {
if (x >= i) s += '*';
else s += ' ';
s += ' ';
}
s.pop_back();
cout << s << endl;
}
s.clear();
for (char ch = 'A'; ch <= 'Z'; ch++) {
s += ch;
s += ' ';
}
s.pop_back();
cout << s;
return 0;
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1), n n n为字符总个数。