例如,我想在 trie 中插入“一些”,但我不知道該怎么做。它給出了一個錯誤,如圖所示(陣列的長度等于 29)。
public void insertWord(String wordName){
for (int i = 0; i < wordName.length(); i ){
if( current.children[wordName.charAt(i) - 'a'] == null)
current.children[wordName.charAt(i) - 'a'] = new Node(wordName.charAt(i));
current = current.children[wordName.charAt(i) - 'a'];}}
執行緒“主”java.lang.ArrayIndexOutOfBoundsException 中的例外:索引 -65 超出長度 29 的范圍
uj5u.com熱心網友回復:
問題是您children使用運算式定義陣列的索引wordName.charAt(i) - 'a'。但是一個空間的序數值比 的小很多'a',所以它變成了一個負值。
相反,您可以在常量字串的幫助下定義從字符到索引的轉換:
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz ";
注意后面的空格z。您可以添加更多字符,如果您想支持其他字符,如逗號、點、...大寫字母、...等。但是,這個字串的長度不應該大于children陣列的長度。
然后,在您的函式中,您可以按如下方式使用該字串:
int key = ALPHABET.indexOf(wordName.charAt(i));
if( current.children[key] == null)
current.children[key] = new Node(wordName.charAt(i));
current = current.children[key];
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421130.html
標籤:
上一篇:列印字串中重復次數最多的單詞
