题解 | #名字的漂亮度#
名字的漂亮度
http://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3
用了两种办法解决,思路大体一致,都是统计数据计算值 方法一:
#include <memory.h>
#include <algorithm>
#include <string>
using namespace std;
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
int n;
int alp[26];
cin >> n;
for(int i = 0; i < n; i++) {
string str;
int value = 26, result = 0;
cin >> str;
memset(alp, 0, sizeof(alp));
for (int i = 0; i < str.length(); i++) {
str[i] = tolower(str[i]);
int index = str[i] - 'a' + 0;
alp[index] += 1;
}
// 不考虑每个具体那个值出现的个数,直接从大到小计算总体最大值值
sort(alp, alp+26, cmp);
for (int i = 0; i < 26; i++) {
result += alp[i] * value;
value--;
}
cout << result << endl;
}
}
方法二:啰嗦点统计具体值对应的大小,思路和上面一样,但是麻烦很多,感觉多次一举
#include <map>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
bool cmpMapValue(const pair<char, int> PAIR1, const pair<char, int> PAIR2)
{
return PAIR1.second > PAIR2.second;
}
int nameNumber(string str)
{
map<char, int>alpCount;
int value = 26, result = 0;
for (int i = 0; i < str.length(); i++) {
if (alpCount.count(str[i]) == 0)
alpCount.insert(pair<char, int>(str[i], 1));
else
alpCount[str[i]] += 1;
}
vector<pair<char, int>> saveData(alpCount.begin(), alpCount.end());
sort(saveData.begin(), saveData.end(), cmpMapValue);
for(auto c = saveData.begin(); c != saveData.end(); ++c) {
result += c->second * value;
if (value > 1)
value--;
}
return result;
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++) {
string str;
cin >> str;
cout << nameNumber(str) << endl;
}
}