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

题目详情

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

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


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




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会唱歌的老樊

老少爷们,来个赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值