我已經或多或少地完成了我的代碼,它可以處理大多數字母的組合。只有輸入「iiiaa」之類的東西纔會失敗。它返回的是'a'發生得最多,但是像「aaaii」這樣的返回結果'a'也是最多的。我認爲這個問題與某種數值有關,因爲如果我列出並在字母「a」之後連續2次或更多次,則會出現問題。 我的代碼目前是:你如何獲得最大價值作爲回報?
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返回次信出現在字量
我收回我所說的可能是一個價值問題。我認爲它必須與char max_char作爲'a'開始 –
解決您嘗試解決的問題會很有用。 –
如果counter> max_counter然後在if中設置max_counter並且你應該完成。 – maraca