我正试图在Java中实现一个非常简单的Trie,它支持3个操作。我希望它有一个插入方法,一个has方法(也就是trie中的某个单词)和一个toString方法以字符串形式返回trie。我相信我的插入工作正常,但已经和toString证明是困难的。这是迄今为止我所拥有的。Trie实现
trie类。
public class CaseInsensitiveTrie implements SimpleTrie {
//root node
private TrieNode r;
public CaseInsensitiveTrie() {
r = new TrieNode();
}
public boolean has(String word) throws InvalidArgumentUosException {
return r.has(word);
}
public void insert(String word) throws InvalidArgumentUosException {
r.insert(word);
}
public String toString() {
return r.toString();
}
public static void main(String[] args) {
CaseInsensitiveTrie t = new CaseInsensitiveTrie();
System.out.println("Testing some strings");
t.insert("TEST");
t.insert("TATTER");
System.out.println(t.has("TEST"));
}
}
和节点类
public class TrieNode {
//make child nodes
private TrieNode[] c;
//flag for end of word
private boolean flag = false;
public TrieNode() {
c = new TrieNode[26]; //1 for each letter in alphabet
}
protected void insert(String word) {
int val = word.charAt(0) - 64;
//if the value of the child node at val is null, make a new node
//there to represent the letter
if (c[val] == null) {
c[val] = new TrieNode();
}
//if word length > 1, then word is not finished being added.
//otherwise, set the flag to true so we know a word ends there.
if (word.length() > 1) {
c[val].insert(word.substring(1));
} else {
c[val].flag = true;
}
}
public boolean has(String word) {
int val = word.charAt(0) - 64;
if (c[val]!=null && word.length()>1) {
c[val].has(word.substring(1));
} else if (c[val].flag==true && word.length()==1) {
return true;
}
return false;
}
public String toString() {
return "";
}
}
因此,基本上,创造了特里的时候,一个TrieNode作为与26名儿童的根目录中创建。当试图插入时,在该根节点上调用insert,递归地在正确的位置创建一个新节点,并继续直到该单词完成。我相信该方法正常工作。
我的功能非常坏,因为我有由于某种原因在括号外有return语句。我不能在一个else子句中包含它,或者编译器抱怨。除此之外,我认为这种方法应该可以进行一些调整,但我无法想象出我的生活。 toString是我试图解决的一个野兽,但没有任何我扔在它的作品,所以我会离开那个,直到我解决了问题。如果我有工作,我可能会想办法将其重新格式化为toString函数。
int val = word.charAt(0) - 64;是因为输入的每个字符串必须全部大写(我将创建一个字符串格式化函数以确保此后),因此第一个字母的int值 - 64将是它在数组中的位置。即数组索引0是A,所以A = 64,A-64 = 0。B = 65,B-64 = 1等等。
相反的: 'INT VAL = word.charAt(0) - 64;' 你这样做: 'INT VAL =字.charAt(0) - 'A';'! – 2012-01-30 19:30:11
为什么你的trie是26-ary有什么理由吗?为什么你只限于美国大写字母?如果任何键有空格或(奥丁禁止)国际字符,会发生什么? – Enno 2012-05-28 22:00:29
这是我的实现,包括addWord,getWordNumber,listAllDistinctWords,通过以下网址查看:https://github.com/shaogbi/Java/blob/master/datastructure/MyTrie.java – coderz 2014-05-26 13:59:43