我或多或少地完成了我的代码,它适用于大多数字母组合。如果我输入类似“iiiaa”的内容,它就会失败。它返回'a'发生最多,但像“aaaii”这样的东西返回'a'也是最多的。我认为这个问题与某种数值有关,因为如果我列出并写入2次或更多次字母后跟字母'a'就会出现问题。 我的代码目前是:
public static char most_frequent_character(String text)
{
int max_counter = 0;
char max_char = 'a';
for (int i = 1; i < text.length(); i++)
{
char current = text.charAt(i);
int counter = count_occurrences(text, current);
char other_char = text.charAt(i-1);
if (counter>count_occurrences(text, other_char))
{
max_char = current;
}
}
return max_char;
}
count_occurrences返回字母出现在单词
中的次数答案 0 :(得分:2)
if (counter>count_occurrences(text, other_char))
条件错误,因为它确定当前char是最常出现的char,如果它出现的次数多于前一个char。您应该将其与当前最大出现次数进行比较。您已经有一个max_counter
变量来维持当前最大出现次数。你应该使用它。并且循环的索引应该从0开始。
int max_counter = 0;
char max_char = 'a';
for (int i = 0; i < text.length(); i++)
{
char current = text.charAt(i);
int counter = count_occurrences(text, current);
if (counter>max_counter)
{
max_char = current;
max_counter = counter;
}
}
return max_char;
答案 1 :(得分:0)
public static char most_frequent_character(String text)
{
List<Integer> t = new ArrayList<Integer>();
List<Character> t2 = new ArrayList<Character>();
//int max_counter = 0;
//char max_char = 'a';
boolean updated = false;
int indexForChar =0;
for (int i = 0; i < text.length(); i++)
{
char other_char = text.charAt(i);
if(t.size()>0)
for(int j=0;j<t.size();j++)
{
if(other_char == t2.get(j))
{
t.set(j, t.get(j)+1);
updated = true;
indexForChar--;
break;
}
}
if(!updated)
{
t.add(1);
t2.add(indexForChar, other_char);
}
updated = false;
indexForChar++;
}
int max = 0;
int index = 0;
for(int j=0;j<t.size();j++)
{
if(max<t.get(j))
{
max = t.get(j);
index= j;
}
}
return t2.get(index);
}