个人笔记-C#-字符出现次数统计

261 阅读1分钟

输入一个字符串,找到该字符串中出现次数最多的字符,并输出该字符出现的次数(区分大小写)。例如:输入acaa,其中a出现的次数最多,并且出现的次数为3,那么我们最后的输出为3输入abc,其中3个字符串出现的次数都为1,那我们输出为1

输入描述

输入只包含大小写字母的字符串,字符串的长度小于1000,并且字符串不为空。

输出描述

输出出现次数最多的字符出现的次数,区分大小写

示例1

输入

abcaABC

输出

2

说明 a出现的次数最多,且次数为2

using System;
using System.Collections.Generic;

namespace MostCommonCharCount
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine().Trim();
            int result = MostCommonCharCount(input);
            Console.WriteLine(result);
        }

        static int MostCommonCharCount(string input)
        {
            Dictionary<char, int> charCount = new Dictionary<char, int>();

            foreach (char c in input)
            {
                if (charCount.ContainsKey(c))
                {
                    charCount[c]++;
                }
                else
                {
                    charCount[c] = 1;
                }
            }

            int maxCount = 0;
            foreach (int count in charCount.Values)
            {
                if (count > maxCount)
                {
                    maxCount = count;
                }
            }

            return maxCount;
        }
    }
}