我有一个TrieNode类,它定义了我的trie节点。 我有一个使用TrieNode构建trie的trie类。 我的意图是在字符串中插入字符串。我不明白为什么我的程序输出为null。有一些非常根本的错误,我无法抓住!在主类中搜索返回false ...我期待是真的。下一个for循环对x的每个值都返回false。我期待x = 7的'not null',因为'h'存储在7。
TrieNode类:
package trie;
public class TrieNode {
int colour;
char letter;
TrieNode child[];
public TrieNode(int colour, char letter, int len){
this.colour = colour;
this.letter = letter;
this.child = new TrieNode[len];
}
public TrieNode(int len){
this.colour = 0;
this.letter = '\\';
this.child = new TrieNode[len];
}
public int getColour(){
return this.colour;
}
public void setColour(int colour){
this.colour = colour;
}
public char getLetter(){
return this.letter;
}
public void setLetter(char letter){
this.letter = letter;
}
public TrieNode getChild(int x){
return this.child[x];
}
}
My Trie Class:
package trie;
public class Trie {
TrieNode root;
public Trie(int len){
root = new TrieNode(len);
}
public void insert(String str){
str = str.toLowerCase();
int length = str.length();
TrieNode temp = root;
for (int x = 0; x < length; x++){
char ch = str.charAt(x);
temp = temp.getChild((int)ch-97);
System.out.println((int)ch-97);
if(temp==null){
temp = new TrieNode(0,ch,26);
}
if(temp!=null){
System.out.println(temp.getLetter());
}
if(x==length-1){
temp.setColour(1);
}
}
}
public boolean search(String str){
str = str.toLowerCase();
int length = str.length();
TrieNode temp = root;
for(int x = 0; x<length; x++){
char ch = str.charAt(x);
temp = temp.getChild((int)ch-97);
if(temp==null || (x==length-1 && temp.getColour()==0)){
return false;
}else{
System.out.println(temp.getLetter());
}
}
return true;
}
}
主要课程:
package trie;
public class Main {
public static void main(String[] args) {
Trie trie = new Trie(26);
trie.insert("hello");
System.out.println(trie.search("hello"));
for(int x=0;x<=25;x++){
System.out.println(x+" "+trie.root.getChild(x));
}
}
}
答案 0 :(得分:0)
您从未向TrieNode child[];
设置任何内容,因此它始终是TrieNode
类型的null数组。
答案 1 :(得分:0)
您的错误在这里:
this.child = new TrieNode[len];
首先,您将在此数组中设置每个TriNode,换句话说,如果您尝试此代码:
public TrieNode getChild(int x){
System.out.println("Child["+x+"] "+this.child[x]);
return this.child[x];
}
你会发现所有的孩子都是空的!!!!