尝试在 java 中打印 trie 中的所有单词
Trying to print all words in a trie in java
我正在使用一种称为字典树的 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);
}
}
}
在此之后,当查找所有单词时,我遍历每个节点并尝试将单词添加到静态数组列表中,但是,由于某种原因,许多单词重复而其他单词丢失。
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;
}
我不明白为什么。
我不知道 DictionaryTree 是什么,也不知道你的 indata 长什么样,但如果你知道的话
children.put(currentPortion.charAt(0), a);
这是否意味着每当你得到一个以与前一个单词相同的字符开头的单词时,旧单词可能会被新单词替换?
要完全理解您使用未知数据类型和所有递归调用的代码是非常不可能的。
我正在使用一种称为字典树的 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);
}
}
}
在此之后,当查找所有单词时,我遍历每个节点并尝试将单词添加到静态数组列表中,但是,由于某种原因,许多单词重复而其他单词丢失。
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;
}
我不明白为什么。
我不知道 DictionaryTree 是什么,也不知道你的 indata 长什么样,但如果你知道的话
children.put(currentPortion.charAt(0), a);
这是否意味着每当你得到一个以与前一个单词相同的字符开头的单词时,旧单词可能会被新单词替换?
要完全理解您使用未知数据类型和所有递归调用的代码是非常不可能的。