题解 | #名字的漂亮度#

名字的漂亮度

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")

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-19 17:02
鼠鼠深知pdd的强度很大,但是现在没有大厂offer,只有一些不知名小厂我是拒绝等秋招呢,还是接下?求大家帮忙判断一下!
水中水之下水道的鼠鼠:接了再说,不图转正的话混个实习经历也不错
投递拼多多集团-PDD等公司10个岗位 >
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务