【发布时间】:2018-03-06 18:45:48
【问题描述】:
我正在使用一种称为字典树的 trie 结构,我想从中打印所有单词。当我到达单词中的最后一个字母时插入单词时,我将完成的单词存储在字典树中。
private Map<Character, DictionaryTree> children = new LinkedHashMap<>();
private String completeWord;
void insertionHelper(String currentPortion, String fullWord){
if(currentPortion.length() == 1){
if(children.containsKey(currentPortion.charAt(0))){
// do nothing
}else{
this.children.put(currentPortion.charAt(0), new DictionaryTree());
}
this.completeWord = fullWord;
}else{
if(children.containsKey(currentPortion.charAt(0))){
children.get(currentPortion.charAt(0)).insertionHelper(currentPortion.substring(1), fullWord);
}else{
DictionaryTree a = new DictionaryTree();
a.insertionHelper(currentPortion.substring(1), fullWord);
children.put(currentPortion.charAt(0), a);
}
}
}
之后,当查找所有单词时,我遍历每个节点并尝试将单词添加到静态数组 List,但是,由于某种原因,许多单词重复,而其他单词丢失。
String allWordHelper(){
String holder = " ";
for (Map.Entry<Character, DictionaryTree> child : children.entrySet()) {
if(completeWord != null){
//holder += completeWord + child.getValue().allWordHelper();
Word_Holder.allWords.add(completeWord);
}else{
holder += child.getValue().allWordHelper();
}
}
return holder;
}
我不知道为什么。
【问题讨论】:
标签: java dictionary tree trie