一个简单而又常见的题目

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

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

 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