C#-hduoj-1004-let the balloon rise

http://acm.hdu.edu.cn/showproblem.php?pid=1004

用字典统计每个字符串出现的次数。

输入

有多个案例,每个案例的第一行是一个整数n,表明下面有n行,每一行是n个字符串。

当n是0是,表示案例结束。

输出:

对于每个案例,输出出现次数最多的字符串。

 

要点:

1、用哈希表存储字符串对应的次数。如果用顺序表,时间复杂度大约为o(n*n),速度慢。

2、字典定义。Dictionary<string, int> color_count = new Dictionary<string, int>();

其本质是哈希表。

3、判断字典中是否存在某个key。

if (color_count.ContainsKey(color))

{

}

4、key对应的数值增1. color_count[color] += 1;

5、寻找值最大的key

int max_val = 0;
                string max_color="";
                foreach (KeyValuePair<string, int> kvp in color_count)
                {
                    if(kvp.Value>max_val)
                    {
                        max_val = kvp.Value;
                        max_color = kvp.Key;
                    }
                }
                Console.WriteLine(max_color);

完整代码如下:

using System;
using System.Collections.Generic;

namespace test
{
    class Program
    {
        
        static void Main(string[] args)
        {
            while (true)
            {

                string s = Console.ReadLine();
                int x = int.Parse(s);//输入共有多少行   
                if (x == 0)
                    return;

                Dictionary<string, int> color_count = new Dictionary<string, int>();

                for (int i = 0; i < x; i++)
                {
                    string color = Console.ReadLine();


                    if (color_count.ContainsKey(color))
                    {
                        color_count[color] += 1;
                    }
                    else
                    {
                        color_count[color] = 1;
                    }

                }
                int max_val = 0;
                string max_color="";
                foreach (KeyValuePair<string, int> kvp in color_count)
                {
                    if(kvp.Value>max_val)
                    {
                        max_val = kvp.Value;
                        max_color = kvp.Key;
                    }
                }
                Console.WriteLine(max_color);
            }



        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值