题解 | #名字的漂亮度#
名字的漂亮度
https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//名字类
class Names {
private:
//名字个数
int N;
//名字
vector<string> names;
public:
//构造函数
Names(const int N);
//析构函数
~Names();
//第i个名字最大可能的漂亮度
const int maxPossibleBeautyOftheIthName(const int i)const;
//第i个名字中字符ch的数量
const int numOfChar(const int i, const char ch)const;
//打印所有名字的最大可能漂亮度
void printBeauty(void)const;
};
Names::Names(const int N) {
this->N = N;
this->names.clear();
string name;
for (int i = 0; i < N; i++) {
cin >> name;
this->names.push_back(name);
}
return;
}
Names::~Names() {
}
const int Names::maxPossibleBeautyOftheIthName(const int i) const {
int beauty = 0;
//用于存储字母个数
vector<int> num;
num.clear();
int n = 0;
for (char ch = 'a'; ch <= 'z'; ch++)
if ((n = this->numOfChar(i, ch)) > 0)
num.push_back(n);
//排序,从小到大
sort(num.begin(), num.end());
//计算最大可能漂亮度
int j = 26;
for (vector<int>::reverse_iterator vit = num.rbegin(); vit != num.rend(); vit++)
beauty += (*vit) * (j--);
return beauty;
}
const int Names::numOfChar(const int i, const char ch) const {
int num = 0;
//遍历字符串
for (char c : this->names[i])
if (c == ch)
num++;
return num;
}
void Names::printBeauty(void) const {
for (int i = 0; i < this->N; i++)
cout << this->maxPossibleBeautyOftheIthName(i) << endl;
return;
}
int main() {
int a, b;
while (cin >> a) { // 注意 while 处理多个 case
Names n(a);
n.printBeauty();
}
}
// 64 位输出请用 printf("%lld")
查看27道真题和解析