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也是错误的

解决方案 »

  1.   

    感觉上面那篇文章的代码求出的数组每个元素都是一样的:
     public static int[] getTopLettersByNum(int[] frequency, int num) {
            // 求出字母出现过一次(或以上)的实际有效字母个数
            int validLength = getValidLettersLength(frequency);        int[] tops = null;
            // 实际有效字母个数如果小于num,直接根据实际有效字母数创建数组
            if (validLength < num) {
                tops = new int[validLength];
            } else {
                tops = new int[num];        }
            for (int i = 0; i < tops.length; i++) {
                int max = -1;
                int maxIndex = 0;
                for (int j = 0; j < frequency.length; j++) {                if (frequency[j] > max) {
                        max = frequency[j];
                        maxIndex = j;
                    }            }            tops[i] = maxIndex;
                frequency[maxIndex] = -1;        }
            return tops;
        }