1004/找出现最多的字符串

HDOJ 1004

题目描述:

输入:第一行输入气球的个数,以下n行是n个气球的颜色,n为0时结束

输出:最多相同颜色的气球的颜色


自己的代码如下:

# include <iostream>
# include <malloc.h>
# include <string.h>
using namespace std;


int main()
{
	int n,j,t,k,num;
	int i;
	int max,t_max;
	char * str[1000];
	while(cin>>n && n!= 0)		
	{
	
		t = n;
		i = 0;

		while(t--)
		{
			char * t_str = (char *)malloc(sizeof(char) * 15);
			*(str + i) = t_str;
			cin>>*(str+i);
			++i;
		}

		max = t_max = 0;
		num = 0;

		for(j = 0; j < n; ++j)
		{
			t_max = 0;
			for(k = 0;k < n; ++k)
			{	
				if(strcmp(*(str+j),*(str+k)) == 0)
					t_max++;
				if(t_max > max)
				{
					max = t_max;
					num = j;
				}
			}
		}
		cout<<*(str+num)<<endl;

		for(j = 0;j<n;++j)
		    	free(*(str+j));
		
	}
	return 0;
}

他人代码参考:

# include <iostream>
# include <string>
using namespace std;
int main()
{
	int i,j,n,count[1000],category;//n为气球数目,category为气球种类数目
	char balloon[1000][15];//用于存储至多1000个气球的颜色字符串
	char temp[15];//用于暂存输入的颜色字符串
	bool change;
	while(cin>>n && n!=0)
	{
		memset(count,0,1000);
		category=0;
		for(i=0;i<n;i++)
		{
			cin>>temp;
			change=false;
			for(j=0;j<i;j++)
			{
				if(strcmp(balloon[j],temp)==0)
				{
					count[j]++;
					change=true;
				}
			}
			if(!change)
			{
				strcpy(balloon[i],temp);
				count[i]++;
				category++;
			}
		}
		int max=0;
		for(i=0,j=0;i<category;i++)//寻找颜色最多的气球
			if(max<count[i])
			{
				max=count[i];
				j=i;
			}
		cout<<balloon[j]<<endl;
	}
	return 0;
}

他人代码适用范围较广,比较典型,统计出不同气球的颜色及其个数,在统计最多的颜色相同的气球的颜色

题目比较简单,自己体会

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值