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;
}

他人代碼適用範圍較廣,比較典型,統計出不同氣球的顏色及其個數,在統計最多的顏色相同的氣球的顏色

題目比較簡單,自己體會

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章