c#使用Dictionary统计字符串中出现次数最多字符

最近在找工作,遇到这样一道面试题:

对于给定的一个字符串,统计出该串中各个字符出现的次数,并打印出出现次数最多的那个字符

因为本人是个菜鸟,所以当时写的思路是用递归

/*str 字符串, strA 第一个字符, strB数量最多的字符,MaxNum数量*/
static void GetLength(string str, string strA, string strB, int MaxNum)
{
  if (str.Length <= 0)
  {
    Console.WriteLine(strB);
    return;
  }

  strA = str.Substring(0, 1);
  int Num = 0;
  string strReplace = "";
  strReplace = str.Replace(strA, "");
  Num = str.Length - strReplace.Length;
  if (Num > MaxNum)
  {
    strB = strA;
    MaxNum = Num;
  }
  GetLength(strReplace, strA, strB, MaxNum);

}

但是后来,问了一些朋友,说递归算法其实效率会很低,用map就行了。于是,使用c#的Dictionary来实现了字符串统计

string str = "jintiantianqihaoqinglang";
Dictionary<char,int> dic=new Dictionary<char,int>();
foreach (char ch in str)
{
  if (dic.Keys.Contains(ch))
  {
    dic[ch]++;
  }
  else
  {
    dic.Add(ch, 1);
  }

}

再取dic中values值最大的key即为出现次数最多的字符

我写的不是最好的方法,也希望各位大神多多提意见,嘻嘻,不过不喜勿喷!!!!

原文地址:https://www.cnblogs.com/BeeSnow/p/5436436.html