某知名IT公司最近的一道笔试编程题(C#)

给定任一字符串(可以有中文),长度为任意,要求找出其出现次数最多的字符及计算次数。 

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值