【问题标题】:Trying to print all words in a trie in java试图在java中打印所有单词
【发布时间】: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


    【解决方案1】:

    我不知道 DictionaryTree 是什么以及你的 indata 是什么样的,但如果你知道的话

    children.put(currentPortion.charAt(0), a);
    

    这是否意味着每当您得到一个与前一个单词以相同字符开头的单词时,旧单词可能会被新单词替换?

    完全理解具有未知数据类型和所有递归调用的代码是完全不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 2017-08-25
      • 2022-11-25
      • 2012-11-16
      • 2017-07-18
      相关资源
      最近更新 更多