zoukankan      html  css  js  c++  java
  • 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即为出现次数最多的字符

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

  • 相关阅读:
    iOS 获取手机当前所连接的网络的IP地址
    np.delete详解
    np.concatenate函数
    说说如何在 Python 中使用日志
    Python os.getcwd() 方法
    python的构造函数
    python引入自己写的Py文件
    VS CODE编译Python输出中文乱码
    VScode中pytorch出现Module 'torch' has no 'xx' member错误
    matlab处理hd5高维数据
  • 原文地址:https://www.cnblogs.com/BeeSnow/p/5436436.html
Copyright © 2011-2022 走看看