看了网上的几篇答案,用的都是排序然后整理出答案。题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1004
以下是我的思路:首先自然是把输入存进一个二维字符串数组。当然,数组中不会有相同的字符串。然后设一个整型数组,下标与字符串数组相对应,整型数组的内容是每一个字符串的个数。这样就算是整理好数据了。
#include<stdio.h>
#include<string.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF && n!=0 ){
char str[20];
char color[1005][20];
int number[1005]={0},j,count=0; //这里的count是用来记录字符串个数的(不一样的字符串个数);
memset(str,0,sizeof(str));
memset(color,0,sizeof(color));
memset(number,0,sizeof(number));
for(int i=0; i<n; i++){
int t,flag=1;//flag为一个标识;
scanf("%s",str);
for(j=0; j<i+1; j++){
if( strcmp(str , color[j])==0 ){
flag=0;
number[j]++;
break;
}//看看新输入的这个字符串在字符串数组是否已经存在,存在相应的整形数组+1并且flag做好标志转换。
}
j--;
if(flag == 1){
strcpy(color[j],str);
number[j]++;
count++;
}//不存在就存进字符串数组;此时count才+1进行记录;
}
int max=0,t=0;
for(int i=0; i<count; i++){//这里count能减少循环次数,也可以换成输入的数据个数n;
if(number[i] > t){
max = i;//max记录的是下标;
t = number[i];//t记录下表对应的内容;
}
if(number[i] == t)
{
if( strcmp(color[i],color[max]) < 0 )
max = i;//碰到一样的个数,取字典序小的;
}
}
printf("%s\n",color[max]);
}
}