ACM——hdu1004(求出现次数最多的字符串)

Problem Description
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges’ favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.

This year, they decide to leave this lovely job to you.
(又是比赛时间了!看到气球飘来飘去真让人兴奋。但是要告诉你一个秘密,评委们最喜欢的时间是猜测最受欢迎的问题。比赛结束后,他们会数一数每种颜色的气球并找到结果。今年,他们决定把这份可爱的工作留给你。)

Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) – the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.

A test case with N = 0 terminates the input and this test case is not to be processed.
(输入包含多个测试用例。每个测试用例从一个数字N开始(0< N<= 1000)—— 即气球的总数。下面N行每行包含一种颜色。气球的颜色是最多15个小写字母的字符串。)

Output
For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.
(对于每一种情况,在单行上打印最流行的气球颜色。保证每个测试用例都有唯一的解决方案。)

Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0

Sample Output
red
pink

题目分析

这道题就是一道求出现次数最多的字符串的问题

解题思路
  1. 用二维数组存储输入的字符串;
  2. 用一维数组存储每种颜色字符串数量;
  3. 每输入一个字符串,便将其与之前的字符串进行比较,如果与之前的字符串相等则为已经出现的颜色,之前的颜色数量加1,标志位flag置1,跳出循环,不用进行接下来的比较;
  4. 判断标志位flag,若flag为0,则此字符串第一次出现,这个颜色数量加1;
  5. 比较得出字符串数量最大的字符串并输出。

Submission

#include <stdio.h>
#include <string.h>
int main() {
    int m,n,x,i,j,max,index,flag;
    char col[1001][16]={0};
    int cnum[1001]={0}; 
    while(scanf("%d",&n)!=EOF)
    {  
        if(n==0) break;
        scanf("%s",col[0]); 
        cnum[0]=1;
        for(i=1;i<n;i++)
        {
            cnum[i]=0;
            flag=0;
            scanf("%s",col[i]);
            for(j=0;j<i;j++)
            {
                if(strcmp(col[i],col[j])==0)
                {
                    cnum[j]+=1;
                    flag=1;
                    break;
                }
            }
            if(flag==0) cnum[i]=1;
        }
    max=cnum[0];
    index=0;
    for(i=1;i<n;i++)
    if(max<cnum[i])
    {
        max=cnum[i];
        index=i;
    }
    printf("%s\n",col[index]);
   } 
    return 0;
}

此处应该注意strcmp函数的使用方法如下:
函数原型为 int strcmp(const char s1,const char s2)
函数功能为两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。当s1< s2时,返回负数;当s1==s2时,返回零;当s1> s2时,返回正数。
注意:这里面只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值