Find character with most occurrences in string?

前端 未结 10 1054
一生所求
一生所求 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:53

    This is Femaref's solution modified to return multiple letters if their Count matches. Its no longer a one-liner but still reasonably concise and should be fairly performant.

        public static IEnumerable GetMostFrequentCharacters(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return Enumerable.Empty();
    
            var groups = str.GroupBy(x => x).Select(x => new { Letter = x.Key, Count = x.Count() }).ToList();
            var max = groups.Max(g2 => g2.Count);
            return groups.Where(g => g.Count == max).Select(g => g.Letter);
        }
    

提交回复
热议问题