日期:2014-05-18  浏览次数:20835 次

(我的代码错在哪)输出出现次数最多的字母,请问怎样保证输入相同最多(aabb)时,结果输出a2b2而不是输出一个?
C# code


            string s = Console.ReadLine();
            char[] charArr = s.ToCharArray();
            int[] frequency = new int[26];
            int[] top =new int[26];//top[0]表示a,top[1]表示b
            int[] topTimes=new int[26];//存储出现的次数
            int maxIndex = 0;
            int max = 0;
            for (int i = 0; i < charArr.Length; i++)
            {
                if (charArr[i] >= 'a' && charArr[i] <= 'z')
                {
                    frequency[charArr[i] - 'a']++;
                }
             }
            for (int j = 0; j < top.Length; j++)
            {
                for (int i = 0; i < frequency.Length; i++)
                {
                    if (frequency[i] > max)//输入aabb,如果大于号输出a,2;如果大于等于号输出b2,但是我的结果是要输出a,2;b,2;因为a,b的数量都是最多
                    {
                        max = frequency[i];
                        maxIndex = i;
                    }

                }
                top[j] = maxIndex;
                topTimes[j] = max;
                if (j != 0) 
                {
                    if (topTimes[j] != topTimes[j - 1]) //如果不存在相同数量的字母,则推出
                        break;
                }

            } 
            Console.WriteLine("出现次数最多的是" + (char)('a' + top[0]) + ",出现的次数为" + topTimes[0]);
            Console.WriteLine("比较输出是否出现重复的数:");
            for (int i = 1; i < top.Length; i++)
            {
                if (topTimes[i] ==topTimes[i - 1])
                    Console.WriteLine("出现次数最多的是" + (char)('a' + top[i]) + ",出现的次数为" + topTimes[i]);
                else
                    break;
            }
                Console.ReadLine();     
        }



参考了这篇文章,怎么感觉里面的getTopLettersByNum也是错误的

------解决方案--------------------
用泛型存储不就行了吗