您的位置:首页 > 其它

字符串的完美度

2013-07-30 17:51 120 查看
题目详情

我们要给每个字母配一个1-26之间的整数,具体怎么分配由你决定,但不同字母的完美度不同,

而一个字符串的完美度等于它里面所有字母的完美度之和,且不在乎字母大小写,也就是说字母F和f的完美度是一样的。

现在给定一个字符串,输出它的最大可能的完美度。

例如:dad,你可以将26分配给d,25分配给a,这样整个字符串最大可能的完美度为77。

函数头部

C

int perfect(const char *s);

C++

int perfect(const string &s);

java

public static int perfect(String s);

下面是我用C语言写的程序

#include<stdio.h>

int perfect(const char *s)
{
const char *p = s; char temp[26];
int k = 0, count[26], i, temnum, biggest = 0;
while(k < 26)
{
temp[k] = 'a' + k;
count[k++] = 0;
}
while(*p != '\0')
{
k = 0;
while((*p != temp[k]) && (*p != temp[k] - 32))
{
k++;
}
count[k]++;
p++;
}

//从高下标端到低下标端进行冒泡排序
for(k = 25; k > 0; k--)
{
for(i = 25; i > 25 - k; i--)
{
if(count[i] > count[i - 1])
{
temnum = count[i]; count[i] = count[i - 1]; count[i - 1] = temnum;
}
}
}

//输入排序后的数组,以查看排序是否成功
for(i = 0; i < 26; i++)
{
printf("%d ", count[i]);
}
printf("\n");

for(temnum = 26, i = 0; count[i] != 0; i++)
{
printf("%d ", count[i]);
biggest += count[i] * temnum--;
}
printf("\n");
return biggest;
}

int main()
{
char mstr[100],pstr[26];
int biggest;
printf("Please input a string:\n");
scanf("%s", mstr);

biggest = perfect(mstr);
printf("The biggest perfect number is %d\n", biggest);

return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息