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也是错误的
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也是错误的
解决方案 »
- Study WPF
- C#的GridView嵌套问题
- 求助!帮我看一下,这样传参数对吗?
- 怎么实现在groupbox里遍历里面的checkbox
- 请问如何找到已知记录的上一条记录和下一条记录?
- 急救!!!谁用过Authorize.net for aim这个东东??
- C#的前途是什么?
- 如何用ASP.net搭建通过支付宝付款的平台!立即结帐!
- 求助,关于打印?
- 请问: 如何在c#中调用API,如FindWindow()
- C#怎么判断滚动条到达最右边呢?
- 一个很纠结的问题—— 字符串加密 byte数组 Hash 散列 算法问题,其实提到这个 或许很多人 和我一样会感到头痛...这里劳烦大神给讲解讲解。。。
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;
}