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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值