所以我正在測試一些來自互聯網的關於Digital Tries的代碼,因爲我有一個項目,嘗試返回此錯誤:數字化嘗試(JAVA) - 線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:-13
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -13
這是我發現這個代碼(Code Source)
TrieNode.java
class TrieNode {
TrieNode[] arr;
boolean isEnd;
// Initialize your data structure here.
public TrieNode() {
this.arr = new TrieNode[26];
}
}
Trie.java
public class Trie {
private TrieNode root;
public static void main(String[] args) {
Trie tr = new Trie();
tr.insert("TEST");
System.out.println("TEST " + tr.search("TEST"));
}
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode p = root;
for(int i=0; i<word.length(); i++){
char c = word.charAt(i);
int index = c-'a';
if(p.arr[index]==null){
TrieNode temp = new TrieNode();
p.arr[index]=temp;
p = temp;
}else{
p=p.arr[index];
}
}
p.isEnd=true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode p = searchNode(word);
if(p==null){
return false;
}else{
if(p.isEnd)
return true;
}
return false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode p = searchNode(prefix);
if(p==null){
return false;
}else{
return true;
}
}
public TrieNode searchNode(String s){
TrieNode p = root;
for(int i=0; i<s.length(); i++){
char c= s.charAt(i);
int index = c-'a';
if(p.arr[index]!=null){
p = p.arr[index];
}else{
return null;
}
}
if(p==root)
return null;
return p;
}
}
輸出:
編譯:
javac TrieNode.java Trie.java
java Trie
任何想法來解決這個問題?
你已經確診的問題,現在添加一個解決方案。 – rgettman
我可以用什麼來代替? int index = c - '0'? –
@rgettman他沒有要求解決方案。事實上,他並沒有要求任何事情! –