华为机试 HJ45题解 | #名字的漂亮度#

名字的漂亮度

https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <unordered_map>
using namespace std;

typedef pair<char, int> PAIR;

bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) {
    return lhs.second > rhs.second;
}

struct CmpByValue {
    bool operator()(const PAIR& lhs, const PAIR& rhs) {
        return lhs.second > rhs.second;
    }
};

int CalBeatifulRate(const std::string& s) {
    if (s.size() == 0) {
        return 0;
    }
    int maxRateSum = 0;
    map<char, int> sMap;
    for (auto ch : s) {
        sMap[ch]++;
    }
    //把map中元素转存到vector中
    vector<std::pair<char, int>> vec(sMap.begin(), sMap.end());
    // 对sMap按照出现的次数进行排序
    std::sort(vec.begin(), vec.end(), cmp_by_value);
    int maxVal = 26;
    for (int i = 0; i < vec.size(); i++) {
        maxRateSum += (vec[i].second * maxVal);
        maxVal--;
    }

    return maxRateSum;
}

int main() {
    int n;
    string nStr;
    vector<string> sVec;
    getline(cin, nStr);
    n = stoi(nStr);
    for (int i = 0; i < n; i++) {
        string s;
        getline(cin, s);
        sVec.push_back(s);
    }

    for (int i = 0; i < sVec.size(); i++) {
        int res = CalBeatifulRate(sVec[i]);
        std::cout << res << std::endl;
    }

    return 0;
}

全部评论

相关推荐

真烦好烦真烦:豆包润色了自己没看看吗,再说了,都说豆包是愚蠢且勤快的大学生,ds才是聪明的研究生,怎么敢让豆包写论文的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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