C#求单词出现最多的字母及次数

用C#编写以下问题:
【输入格式】 输入一行包含一个单词,单词只由小写英文字母组成。
【输出格式】 输出两行,第一行包含一个英文字母,表示单词中出现得最多的字母是哪个。如果有多个字母出现的次数相等,输出字典序最小的那个。第二行包含一个整数,表示出现得最多的那个字母在单词中出现的次数。

例如输入:
Lanqiao

输出:
a
2

回答

static void Main(string[] args)
{
var str = Console.ReadLine();
var re = GetMaxCountChar(str);
Console.WriteLine(re.Item1);
Console.WriteLine(re.Item2);
}
static Tuple<char, int> GetMaxCountChar(string str)
{
//func 1 linq
var r = str.GroupBy(g => g)
.Select(g => Tuple.Create(g.Key, g.Count()));
var maxCount = r.Max(g => g.Item2);
var c = r.Where(g => g.Item2 == maxCount).Min(g => g.Item1);
return Tuple.Create(c, maxCount);

        //func 2 hash + linq
        var dic = new Dictionary<char, int>();
        foreach (var item in str)
        {
            if (dic.ContainsKey(item))
            {
                dic[item] = dic[item] + 1;
            }
            else
            {
                dic[item] = 1;
            }
        }
        var count = dic.Values.Max();
        var c = dic.Where(item => item.Value == count)
            .Min(item => item.Key);
        return Tuple.Create(c, count);
    }
以上是C#求单词出现最多的字母及次数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>