2016-03-04 69 views
0

我已經或多或少地完成了我的代碼,它可以處理大多數字母的組合。只有輸入「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返回次信出現在字量

+0

我收回我所說的可能是一個價值問題。我認爲它必須與char max_char作爲'a'開始 –

+0

解決您嘗試解決的問題會很有用。 –

+1

如果counter> max_counter然後在if中設置max_counter並且你應該完成。 – maraca

回答

2

if (counter>count_occurrences(text, other_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; 
0

這可能幫助你 中,我們採取的每一個字符決定通過它的索引。並迭代循環直到每個字符都被檢查過。之後迭代到List大小並獲得最大出現次數。

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); 
}