字符串完美度计算的C实现(我自己编译运行正确,编程挑战赛时不管怎么都成功不了,奇了个葩)

来源:互联网 发布:好看的爱情电影 知乎 编辑:程序博客网 时间:2024/04/26 04:30

算法思想:

第一步:利用一个长度26的数组存放每个字母(不分大小写)出现的次数,如count[0]表示a或A的出现的次数;

第二步:统计出现字母的种类数;

第三步:利用一个长度26的数组存放每种字母的完美度权值(出现最多的字母权值为26),权值=(26-字母种类数)+字母出现的次数;

第四步:计算次数与权值乘积的累加和即为字符串的完美度。

#include <stdio.h>
int perfect(const char *s)
{
        int i;//循环变量

        int order=0;//定位变量

        int base=0;//计算基底
        int count[26]={0};//个数数组
        int value[26]={0};//权值数组
        int kind=0;//种类数
        int perfect=0;//完美度
        while((*s)!='\0')//统计各字母个数
        {
        if((*s)>='a')
        order=(int)((*s)-'A'-32);
        else
        order=(int)((*s)-'A');
        count[order]+=1;
        s++;
        }
        for(i=0;i<26;i++)//统计种类数
        {
        if(count[i]>0)
                kind++;
        }
        base=26-kind;//计算基底
       for(i=0;i<26;i++)//计算完美度
        {
        value[i]=base+count[i];
        if(count[i]>0)
                perfect+=count[i]*value[i];
        }
        return perfect;
      }
     int main(void)
    {
        char str[100];
        printf("Input a string: \n");
        scanf("%s",str);
        printf("The perfect num of this string is: %d\n",perfect(str));
        return 0;
     }

 

下面是在Linux下的运行结果: