一个简单而又常见的题目

给出一个任意长度的字符串,求出该字符串中出现频率最高的字符,并算出出现次数。

 面试的时候被问到,这么简单的题目,竟然答不上来。面试一紧张,感觉思路就不顺畅,郁闷死了。这题有两种常见解法。

 public static KeyValuePair<char, int> GetMaxCountChar(string resource)
        {
            IDictionary<char, int> dic = new Dictionary<char, int>();
            foreach (char item in resource)
            {
                if (dic.Keys.Contains(item))
                    dic[item] = dic[item] + 1;
                else
                    dic[item] = 1;
            }  
            int maxCount = 0;
            char maxChar = ' ';
            foreach (var item in dic.Keys)
            {
                if (maxCount < dic[item])
                {
                    maxCount = dic[item];
                    maxChar = item;
                }
            }
            return new KeyValuePair<char, int>(maxChar,maxCount);
        }
View Code

上面这个方法看起来效率会底一点,在字符串足够长的情况下。

public static KeyValuePair<char, int> GetMaxCountChar2(string resource)
        {
            int maxCount = 0;
            char maxChar = ' ';
            foreach (char item in resource)
            {
                var tmp = resource.Split(item);
                if (maxCount < tmp.Length-1)
                {
                    maxChar = item;
                    maxCount = tmp.Length - 1;
                }
            }
            return new KeyValuePair<char, int>(maxChar, maxCount);
        }


各位网友,麻烦告知更好的解法,相信一定有。

 

 

转载于:https://www.cnblogs.com/YangFengHui/p/3338167.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值