C#作业 求最大篮球的单词数

69 阅读1分钟

给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "basketball"(篮球)。 字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "basketball"。

        static int getWordCount(int[] count)
        {
            //定义一个复制数组,存储变化值
            int[] copyCount = new int[count.Length];
            for (int i = 0; i < count.Length; i++)
            {
                //如果有一个为0 则里面没有一个完整的balsket
                if (count[i] == 0)
                {
                    return 0;
                }
                //basketball 里面含有两个b,a,l所以要除于2 ,之前把b,a,l放在了前三个位置
                else if (i  == 0 || i == 1 || i == 2)
                {
                    copyCount[i] = count[i] / 2; 
                }
                else
                {
                    copyCount[i] = count[i];
                }
            }
            //求里面最小值则为单词basketball存在的数量
            int min = copyCount.Min();
            return min;
        }
        static void Main(string[] agrs)
        {
            //定义一个三个数组
            Console.Write("text = ");
            char[] text = (Console.ReadLine().ToLower()).ToCharArray();
            char[] word = "balsket".ToCharArray(); //basketball
            int[] count = new int[word.Length];

            //遍历用户输入的字母
            for (int i = 0; i < text.Length; i++)
            {
                //遍历 balsketbl 字母
                for (int j = 0; j < word.Length; j++)
                {
                    //比较发现里面含有多少个跟 balsketbl 相同的字母
                    if(text[i] == word[j])
                    {
                        //统计相同字母的数量
                        count[j] += 1;
                    }
                }
            }
            //函数计算返回结果
            int result = getWordCount(count);
            Console.WriteLine(result);
        }

image.png