HWOJ 名字的漂亮度
题目:
给出一个名字,该名字有26个字符串组成,定义这个字符串的“漂亮度”是其所有字母“漂亮度”的总和每个字母都有一个“漂亮度”,范围在1到26之间。没有任何两个字母拥有相同的“漂亮度”。字母忽略大小写。给出多个名字,计算每个名字最大可能的“漂亮度”。
题目分析:
算法思路:
①先创建哈希表,之后找出字符串中出现的字母的次数用isalpha来判断是否为字母
②之后将哈希表的键值的值降序,用sort(a,a+n,cmp)来排序
③之后用for循环将那个字母出现的次数最多,出现最多的乘以26,其次出现乘以25;之后乘以24……
④这道题还有一点不一样,就是输出的格式,我们利用指针score来做
===============================================================================
参考代码:
//.cpp
#include <iostream>
#include <algorithm>
#include <ctype.h>
using namespace std;
bool compare(const int a,const int b)
{
return a > b;
}
int getBeauScore(int n,char *str)
{
//输入不合法
if(n < 0)
return 0;
//创建一个哈希表,并且初始化
const int TableSize = 256;
unsigned int hashTable[TableSize];
for(int i = 0;i < TableSize; i++)
hashTable[i] = 0;
//哈希表键值保存给str
char *pHashKey = str;
while(*pHashKey)
{
if(isalpha(*pHashKey))
hashTable[*pHashKey] ++;
pHashKey ++;
}
sort(hashTable,hashTable + 256,compare);
int score = 26;
int scoreSum = 0;
for(int i = 0;i < TableSize; i++)
{
scoreSum += score * hashTable[i];
score --;
}
return scoreSum;
}
int main()
{
char str[1000];
int n,i;
int *score;
cout << "请输入名字的行数:";
cin >> n;
score=(int*)malloc(sizeof(int)*(n+1));
for(i = 1;i <= n; i++)
{
cin >> str;
*(score + i) = getBeauScore(n,str);
}
for(i = 1;i <= n; i++)
cout << *(score + i) << endl;
return 0;
}