给定任一字符串(可以有中文),长度为任意,要求找出其出现次数最多的字符及计算次数。
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
public static void getMaxchar(String s)
{
char[] c = s.ToCharArray();
item[] ht = new item[c.Length]; //最坏的情况下(每个字符均不一样),需要c.Length个存储单元
for (int i = 0; i <= c.Length - 1; i++)
{ //赋初值,防止出现空指针引用 ********小心******
ht[i] = new item();
}
item Maxitem = ht[0];
for (int i = 0; i <= c.Length - 1; i++)
{
int unicode = (int)c[i]; // 获得字符的unicode值 ()
int position = unicode % c.Length; //自定义的Hash函数
if (ht[position].count == 0)
{ //第一次扫描到的字符放入数组中
ht[position].a = c[i];
ht[position].count = 1;
}
else
if (ht[position].a == c[i]) //扫描到了同样的字符,count加1
ht[position].count++;
else
for (int j = position + 1; j != position - 1; position++)
{ //Hash表发生地址冲突,用线形探测法解决地址冲突
if (ht[position].count == 0)
{
ht[position].a = c[i];
ht[position].count = 1; //找到空位置,插入
break;
} // 找到,跳出循环
if (position == c.Length - 1) //往后找,无空位可插入,则往前找
position = 0;
}
}
for (int i = 1; i <= c.Length - 1; i++)
{ //遍历数组,找到一个最大值
if (ht[i].count > Maxitem.count)
Maxitem = ht[i];
}
for (int i = 1; i <= c.Length - 1; i++)
{ //遍历数组,找到所有的最大值,譬如”31212“这种多个最大值情况
if (ht[i].count == Maxitem.count)
Console.WriteLine("出现次数最多的字符是:" + ht[i].a + " 次数是:" + ht[i].count);
}
}
static void Main(string[] args)
{
getMaxchar(("本代码IT5552341985euiollgjIT5riugjkj51ITIT1IT45ITITdjjkklITITdfjIT阳"));
Console.ReadLine();
}
}
class item
{ //定义哈希表中的元素
public char a;
public int count=0;
public item()
{
this.a = ' ';
this.count = 0;
}
}
}