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即为出现次数最多的字符

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

  • 相关阅读:
    oracle ODM 数据挖掘笔记
    oracle 函数3
    清除Oralcle的session的理由和方法
    ORACLE 多表关联 UPDATE 语句
    PL/SQL中游标和游标变量的使用(转)
    Oracle select in/exists/not in/not exits
    实战 BIRT 系列,第 1 部分
    freebsd中查看文件夹/目录大小的方法/命令
    大数据量导出Excel的方案
    我的万能dao设计类图
  • 原文地址:https://www.cnblogs.com/BeeSnow/p/5436436.html
Copyright © 2011-2022 走看看