原题链接
我的解法
题不难,用了一个O(n²)的解法,首先统计出所有字母出现次数,然后找到其中出现最多的次数,从它开始逐级往下输出,也没遇到什么坑(不过最初写的版本里面没注意到每次输出完一行之后maxNum要 - 1
以及最后不知道该怎么从int转成我需要的char,所以只好另开了一个数组来对应字母orz
贴一下代码
#include <iostream>
#include <string>
const int LEN = 26;
const char LETTER[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
using namespace std;
int main() {
string s;
int a[LEN] = { -1 };
for (int i = 0; i < 4; i++) {
getline(cin, s);
for (int i = 0; i < s.length(); i++) {
int tmp = (int)s[i];
if (tmp >= 65 && tmp <= 90) {
if (a[tmp - 65] != -1)
a[tmp - 65]++;
else
a[tmp - 65] = 1;
}
}
}
//print (pay attention: do not print those -1 ones)
//1. find the maximun one in the array
int maxNum = 0;
for (int i = 0; i < LEN; i++) {
if (a[i] > maxNum)
maxNum = a[i];
}
for (int i = maxNum; i > 0; i--) {
for (int j = 0; j < LEN; j++) {
if (a[j] != -1) {
if (a[j] == maxNum && j != LEN - 1) {
cout << "* ";
a[j]--;
}
else if (a[j] == maxNum && j == LEN - 1) {
cout << "*";
a[j]--;
}
else if (a[j] < maxNum && j != LEN - 1) {
cout << " ";
}
else if (a[j] < maxNum && j == LEN - 1) {
cout << " ";
}
}
}
cout << endl;
maxNum--;
}
//最后输出字母
for (int i = 0; i < LEN; i++) {
if (a[i] != -1 && i != LEN - 1) {
cout << LETTER[i] << " ";
}
else if (a[i] != -1 && i == LEN - 1) {
cout << LETTER[i];
}
}
return 0;
}
博客介绍了如何使用C++解决洛谷上的P1598问题,采用了一个O(n²)的时间复杂度解法。作者首先统计每个字母的出现次数,找出最频繁的字母,然后按层次逐行输出。文章中提到最初的代码存在未减少最大次数和字符转换的问题,通过修正这些问题完成了解决方案。
598

被折叠的 条评论
为什么被折叠?



