字符串的完美度

来源:互联网 发布:mysql服务 启动 linux 编辑:程序博客网 时间:2024/04/30 09:35

题目来源:

庞果英雄会

 

题目概述:

我们要给每个字母配一个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);                

题目分析:

很显然,这是一道求字符串中每个字符的重复次数问题。

 

题目解答:

#include "stdafx.h"#include <stdio.h>#include <stdlib.h>#include <string.h>void sort(int *s,int len){    int tems;    int flag;    for (int i = 0; i < len; i++)    {        flag=0;        for (int j = len-1; j > i; j--)        {            if (*(s+j)>*(s+j-1))            {                tems=*(s+j);                *(s+j)=*(s+j-1);                *(s+j-1)=tems;                flag=1;            }            }        if (flag==0)            {                break;            }    }    }int perfect(const char *s) {    int len=strlen(s);    int num[26]={0};    int result=0;    for (int i = 0; i < len; i++)    {        if ((*(s+i)>='A') && (*(s+i)<='Z'))        {            num[*(s+i)-'A']++;        }        if ((*(s+i)>='a') && (*(s+i)<='z'))        {            num[*(s+i)-'a']++;        }        }    sort(num,26);    for (int i = 0; i < 26; i++)    {        if (num[i]==0)        {            break;        }        result+=num[i]*(26-i);    }    return result;}//start 提示:自动阅卷起始唯一标识,请勿删除或增加。int main(){        char str[50]="dad";    int result;    //gets_s(str);    result = perfect((const char *)(&str));printf("The serfect degree is %d \n",result);    //cout<<"The serfect degree is "<<result<<"\n";    return 0;}//end //提示:自动阅卷结束唯一标识,请勿删除或增加。