我正試圖在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