华为oj 等差数列&&字符统计

应该是整个oj中最简单的了吧!

#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
if(n<=0)
{
return -1;
}
cout<<2*n+3*n*(n-1)/2<<endl;
return 0;
}


本题提供两个程序:算法相同只是数据结构不同一个使用的是结构体,一个使用的是map

整体思路需要统计出每个字符的个数,然后根据给出的规则进行排序!!!

程序1

#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
typedef pair<char, int> pp;
bool sortby(pp iter1, pp iter2)
{
	if (iter1.second > iter2.second)
	{
		return true;
	}
	else if (iter1.second < iter2.second)
	{
		return false;
	}
	else
	{
		if (iter1.first < iter2.first)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}
int main()
{
	map<char, int> in;
	char temp[100];
	vector<pair<char, int>> vec;
	gets_s(temp);
	int len = strlen(temp);
	for (int i = 0; i<len; i++)
	{
		in[temp[i]]++;
	}

	
	for (map<char, int>::iterator iter = in.begin(); iter != in.end(); iter++)
	{
		vec.push_back(make_pair(iter->first, iter->second));
	}
	sort(vec.begin(), vec.end(), sortby);
	for (int i = 0; i < vec.size(); i++)
	{
		cout << vec[i].first;
	}
	cout << endl;
	return 0;
}
程序 2

#include<iostream>
#include<algorithm>
using namespace std;

struct Statistic
{
	char letter;
	int count;
};

bool sortby(Statistic a, Statistic b)
{
	if (a.count > b.count)
	{
		return true;
	}
	else if (a.count < b.count)
	{
		return false;
	}
	else
	{
		if (a.letter < b.letter)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}
int main()
{
	char inStr[100];
	int ascii[128],s;
	Statistic out[100];

	gets_s(inStr);
	memset(ascii, 0, sizeof(int)* 128);
	s = 0;

	for (int i = 0; i<strlen(inStr); i++)
	{
		ascii[inStr[i]]++;
	}

	for (int i = 0; i<128; i++)
	{
		if (!ascii[i])
		{
			continue;
		}
		if ((i >= 'a'&&i <= 'z') || (i >= 'A'&&i <= 'Z') || (i >= '0'&&i <= '9') || (i == ' '))
		{
			out[s].letter = i;
			out[s].count = ascii[i];
			s++;
		}
	}

	sort(out, out + s, sortby);

	for (int i = 0; i < s; i++)
	{
		cout << out[i].letter;
	}
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值