2016-11-25 101 views
0

尝试使用字典来实现此目的。目前,我有这样的方法:返回字符串中最常见的字符

/// <summary> 
/// Returns the character(s) with the highest occurence in this string. 
/// </summary> 
/// <param name="str">the tring containing the characters</param> 
/// <returns>the character or characters with the highest occurence</returns> 
static char[] GetMostFrequentChar(string str) 
{ 
    var chars = new Dictionary<char, int>(); 
    List<char> mostCommon = new List<char>(); 
    for (int i = 0; i < str.Length; i++) 
    { 
     if (chars.ContainsKey(str[i])) 
     { 
      int curr = chars[str[i]]; 
      chars[str[i]] = curr + 1; 
     } else // character not in dictionary 
     { 
      chars.Add(str[i], 1); // initial count for an added character is 1 
     } 
    } 
    foreach (KeyValuePair<char, int> entry in chars) 
    { 
     if (entry.Value == chars.Keys.Max()) 
     { 
      mostCommon.Add(entry.Key); 
     } 
    } 
    char[] result = mostCommon.ToArray(); 
    return result; 
} 

它应该返回一个包含最常见的字符(一个或多个)阵列,但我似乎每当我运行一个输入字符串这种方法来获得一个空数组。我哪里做错了?

我知道有些方法可以在没有字典的情况下做到,但我很好奇它如何与字典一起工作。

+7

'如果(entry.Value == chars.Keys.Max())'我认为你的意思是'chars.Values.Max()' –

+0

@KevinGosse我觉得超级愚蠢。非常感谢。这解决了它。 –

回答

1

凯文·戈斯已经给你答案,但你可以简化你的代码有点像这样:

private static char[] GetMostFrequentChar(string str) 
{ 
    Dictionary<char, int> chars = new Dictionary<char, int>(); 

    foreach (char c in str) 
    { 
     if (chars.ContainsKey(c)) chars[c]++; 
     else chars.Add(c, 1); 
    } 

    int max = chars.Values.Max(); 
    return chars.Where(b => b.Value == max).Select(b => b.Key).ToArray(); 
} 
2

只是为了赫克,这里有一个Linq -approach与Dictionary

static char[] GetMostFrequentChar(string str) 
{ 
    Dictionary<char, int> result = str.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count()); 
    return result.Where(x => x.Value == result.Values.Max()).Select(x => x.Key).ToArray(); 
}