//功能:给出一个名字,该名字有26个字符串组成,定义这个字符串的“漂亮度”是其所有字母“漂亮度”的总和,每一个字母都有一个“漂亮度”,范围在1-26之间,没有任何两个字母拥有相同的“漂亮度”,字母忽略大小写。给出多个名字,计算每个名字最大可能的漂亮度
//样例输入:整数N,后续N个名字 2 zhangsan lisi 样例输出:192 101
//基本思路:
运行结果:
2)利用sort语句来排序,通过使用bool compare来控制升降,这里一定要注意加上&
3)细心的同学会注意,最后保存的时候我采用了动态内存分配malloc,意思就是重新定义一个指针,为它定义指向变量定义一个内存;为什么不能直接用上篇博文中提到的return scoreSum;这就和要求输入输出格式有关系。多个输入,多个输出一般采用这种形式。
——To_捭阖_youth 9:04
//样例输入:整数N,后续N个名字 2 zhangsan lisi 样例输出:192 101
//基本思路:
//就是先遍历找出A或者a +(1至26),在每个中加1,这样就可以知道具体字母出现的次数,那个字母出现的次数最多,出现最多的*26,其次出现*25;之后*24……
参考代码:
#include <iostream>
#include <algorithm>
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)
{
for(int j = 0;j <= 26;j ++)
{
if(*pHashKey == 'A' + j || *pHashKey == 'a' + j)
hashTable[*pHashKey] ++;
}
pHashKey ++;
}
sort(&hashTable[0],&hashTable[TableSize - 1],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;
}
运行结果:
算法巧妙之处:
1)通过利用下面语气巧妙找出字母
for(int j = 0;j <= 26;j ++)
{
if(*pHashKey == 'A' + j || *pHashKey == 'a' + j)
hashTable[*pHashKey] ++;
}
2)利用sort语句来排序,通过使用bool compare来控制升降,这里一定要注意加上&
bool compare(const int a,const int b)
{
return a > b;
}
sort(&hashTable[0],&hashTable[TableSize - 1],compare);
3)细心的同学会注意,最后保存的时候我采用了动态内存分配malloc,意思就是重新定义一个指针,为它定义指向变量定义一个内存;为什么不能直接用上篇博文中提到的return scoreSum;这就和要求输入输出格式有关系。多个输入,多个输出一般采用这种形式。
int *score;
score=(int*)malloc(sizeof(int)*(n+1));
*(score + i) = getBeauScore(n,str);
——To_捭阖_youth 9:04