Find character with most occurrences in string?

前端 未结 10 1058
一生所求
一生所求 2020-11-27 17:49

For example, I have a string:

\"abbbbccd\"

b has the most occurrences. When using C++, the easiest way to handle this is inser

10条回答
  •  盖世英雄少女心
    2020-11-27 18:30

    This because someone asked for a 2.0 version, so no LINQ.

    Dictionary dict = new Dictionary();
    
    int max = 0;
    
    foreach (char c in "abbbbccccd")
    {
        int i;
        dict.TryGetValue(c, out i);
        i++;
        if (i > max)
        {
            max = i;
        }
        dict[c] = i;
    }
    
    foreach (KeyValuePair chars in dict)
    {
        if (chars.Value == max)
        {
            Console.WriteLine("{0}: {1}", chars.Key, chars.Value);
        }
    }
    

    Instead this for the LINQ version. It will extract paired "bests" (aaaabbbb == a, b). It WON'T work if str == String.Empty.

    var str = "abbbbccccd";
    
    var res = str.GroupBy(p => p).Select(p => new { Count = p.Count(), Char = p.Key }).GroupBy(p => p.Count, p => p.Char).OrderByDescending(p => p.Key).First();
    
    foreach (var r in res) {
        Console.WriteLine("{0}: {1}", res.Key, r);
    }
    

提交回复
热议问题