字符串的完美度


还是庞果网,又看到一个题目,这个比较简单。


题目详情

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


算法描述


算法没什么可说的,比较简单,先把字符串都变成大写或者小写,然后依次找出出现次数最多的字母,然后最多的分26,次多的分25,依次类推,最后求和,算法难度一颗星。。。。


#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;


struct myclass {
  bool operator() (int i,int j) { return (i>j);}
} myobject;

int howMany(string &str)
{
    if(str.size()==1)
    {
        str.erase(0,1);
        return 1;
    }

    
    if(str.size()==0)
        return 0;
    
    string::iterator it;
    char  cmp=str[0];
    int count=0;
    
    for(int i=0;i<str.size();i++)
    {
        if(cmp==str[i])
        {
            count++;
            str.erase(i,1);
            i--;
        }
    }
    
    return count;
}

int perfect(const string &s) {
    string str=s;
    vector<int> charCounts;
    int count,i,j;
    int perfectNum=0;
    
    transform(str.begin(), str.end(), str.begin(), ::toupper);
    
    do
    {
        count=howMany(str);
        charCounts.push_back(count);
    }while(count>0);
    
    sort(charCounts.begin(),charCounts.end(),myobject);
    
    for(i=0,j=26;i<charCounts.size();i++,j--)
    {
        perfectNum=perfectNum+j*charCounts[i];
        //cout << charCounts[i] << " --- ";
    }
        
    
    //cout << endl;
    //cout << "perfect Num is " << perfectNum << endl;
    return perfectNum;
}


//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{   
    cout << perfect("DAddfdafdfhjfaodnDFESSDF") << endl;
} 
//end //提示:自动阅卷结束唯一标识,请勿删除或增加。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值