給出一個任意長度的字符串,求出該字符串中出現頻率最高的字符,並算出出現次數。面試
面試的時候被問到,這麼簡單的題目,居然答不上來。面試一緊張,感受思路就不暢,鬱悶死了。這題有兩種常看法法。ide
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); }
上面這個方法看起來效率會底一點,在字符串足夠長的狀況下。spa
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); }
各位網友,麻煩告知更好的解法,相信必定有。code