[英]How do I consider a space character in a trie?
例如,我想在 trie 中插入“一些”,但我不知道該怎么做:
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 的范圍
數組的長度等於 29。
我該如何解決這個問題?
問題是您使用表達式wordName.charAt(i) - 'a'
定義children
數組的索引。 但是一個空間的序數值比'a'
的小很多,所以它變成了一個負值。
相反,您可以在常量字符串的幫助下定義從字符到索引的轉換:
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz ";
注意z
后面的空格。 您可以添加更多字符,如果您想支持其他字符,如逗號、點、...大寫字母、...等。 但是,這個字符串的長度不應該大於children
數組的長度。
然后,在您的 function 中,您可以按如下方式使用該字符串:
int key = ALPHABET.indexOf(wordName.charAt(i));
if( current.children[key] == null)
current.children[key] = new Node(wordName.charAt(i));
current = current.children[key];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.