2
我一直在努力計劃如何從trie中刪除單詞。我有一個在節點上使用一維數組的實現,它包含一個單詞的下一個字符。我理解我如何擺脫整個單詞,但不考慮包含較小單詞的較大單詞,以便從以下單詞刪除「bat」,「battle」,「as」和「any」(*表示字的結束),並留下「電池」,「戰場」,「問」和「anywho」:Java - 刪除trie中的單詞(僞代碼)
root
/\
a b-a-t*-t-e-r-y*
/\ |
n s*-k* l-e*-f-i-e-l-d*
|
y*-w-h-o*
下面是迄今爲止我已經實現了特里:
public class TrieNode {
protected char letter = ' ';
protected TrieNode parentNode = null;
protected boolean fullWord = false;
protected TrieNode[] children = new TrieNode[26];
public TrieNode(char letter, TrieNode parentNode){
this.letter = letter;
this.parentNode = parentNode;
}
public boolean hasChildren(){
int index = 0;
while(index < children.length){
if(children[index] != null) {
return true;
}
index++;
}
return false;
}
public TrieNode nodeForLetter(char ch) {
return children[ch - 97];
}
public boolean isEndOfWord() {
return fullWord;
}
}
public class Trie implements Iterable<String> {
private int numOfNodes;
private int numOfWords;
private TrieNode root = new TrieNode(' ', null);
public Trie() {
}
public void addWord(String s) {
if (hasWord(s)) return;
int index = 0;
TrieNode iterator = root;
while(index < s.length()){
if(iterator.children[s.charAt(index) - 97] == null){
iterator.children[s.charAt(index) - 97] = new TrieNode(s.charAt(index), iterator);
numOfNodes++;
}
iterator = iterator.children[s.charAt(index) - 97];
index++;
if(index == s.length()){
iterator.fullWord = true;
numOfWords++;
}
}
}
// Issues on this one
public void deleteWord(String s) {
if(s.length() == 0) return;
// make method to check for empty trie
else if(!(hasWord(s))) return;
else {
TrieNode iterator = root;
int index = 0;
while(index < s.length()){
if(iterator.children[index] != null){
/* What would (in pseudo code) need to be put here to account for this */
}
}
}
}
public boolean hasWord(String s) {
TrieNode current = root;
while(current != null){
for (int i = 0; i < s.length(); i++) {
if(current.letter == ' ') return false; // error here probably
else current = current.children[i];
}
if (current.fullWord == true) return true;
else return false;
}
return false;
}
public Iterator<String> iterator() {
return new TrieIterator(); // has basic iterator functions
}
}
任何人都可以提出一些僞代碼幫我弄明白這一點