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