• 编程挑战:字符串的完美度


    题目详情

    我们要给每个字母配一个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 <iostream>
    #include <string>
    
    using namespace std;
    
    int perfect(const string &s);
    
    int main()
    {
    	
    	while (true)
    	{
    		string str;
    		cout << "Please enter the characters : ";
    		cin >> str;
    
    		if (str == "0") break;
    
    		int result = perfect(str);
    
    		cout << "perfect result of " << result << endl;
    	}
    	return 0;
    }
    
    
    int perfect(const string &s)
    {
    	int ia = (int)'a';	// 97
    	int iA = (int)'A';	// 65
    
    	int perfectNum = 0;
    	string content = s;
    
    	int config[26] = {0};
    	
    	//  获取字符的记录个数
    	while (content.size())
    	{
    		char ch = content[0];
    		while (true)
    		{
    			int index = content.find(content[0]);
    			if (index < 0) break;
    			if ((int)content[0] < ia)
    			{
    				// 大写内容
    				config[(int)content[0] - iA] ++;
    			}
    			else
    			{
    				config[(int)content[0] - ia] ++;
    			}
    			
    			content.erase(index, 1);
    		}
    	}
    	
    	// 将个数进行排序
    	int i,j,t;
    	for(i=0;i<25;i++)
    	{
    		for(j=0;j<25-i;j++)
    		{
    			if(config[j+1]>config[j])
    			{
    				t=config[j+1];
    				config[j+1]=config[j];
    				config[j]=t;
    			}
    		}
    	}
    
    	// 开始进行最大幸福数计算
    	for(int i = 0, momey = 26; i < 26; i ++, momey --)
    	{
    		perfectNum += config[i]*momey;
    	}
    	
    	return perfectNum;
    }

    不知对错带指正,仅供交流!


    以后要切记好好审题哦……
    仅此一次,下次再不会在没有结束挑战之前放代码了。




  • 相关阅读:
    linux vps定时备份网站、数据库命令sh
    zencart批量表上传后 标题显示为网址 批量修改标题状态 SEO三要素
    robots.txt防止向黑客泄露网站的后台和隐私
    在网页中插入地图展示公司地址
    网站调用百度地图 根据地址查询经纬度
    jquery 未来元素事件示例 on() delegate() live()
    .htaccess A网站单页面301到B网站单页面
    linux批量设置部分文件与文件夹权限
    php中禁止单个ip与ip段访问的代码小结
    Spring整合ActiveMQ
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3187009.html
Copyright © 2020-2023  润新知