题解 | #名字的漂亮度# C++参考代码

名字的漂亮度

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

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

int main() {
  // 频次从高到低排序,按照频次赋漂亮度
  int num;
  cin >> num;
  vector<string> strs(num);
  // 收集所有的字符串
  for (int i = 0; i < num; i++) {
    cin >> strs[i];
  }
  for (int i = 0; i < num; i++) {
    auto str = strs[i];
    // 26个小写字母,用于映射频次
    vector<int> chars(26, 0);
    for (auto &c : str) {
      chars[c-'a']++;
    }
    // 按照频次排序
    std::sort(chars.begin(), chars.end(), std::greater());
    int res = 0;
    int degree = 26;
    // 排序高的赋予26漂亮度,依次递减,累加漂亮度直到频次为0或者遍历完成为止
    for (int j = 0; j < chars.size(); j++) {
      if (chars[j] == 0) {
        break;
      }
      res += chars[j] * degree--;
    }
    cout << res << endl;
  }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

2025-12-28 09:59
复旦大学 Java
点赞 评论 收藏
分享
2025-12-26 10:52
河北传媒学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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