【问题标题】:Need to add words in a Trie需要在 Trie 中添加单词
【发布时间】:2023-08-27 14:53:02
【问题描述】:

谁能帮助我如何在 Trie 中添加对数据结构非常新的单词

/**
 * This method adds a word to the Trie
 * 
 * @param s - word to add to the Trie
 * @param data - Data associated with word s
 */
public void addWord(String s, E data) {

}

【问题讨论】:

  • 您打算自己创建 Trie 数据结构吗?
  • 告诉我们你做了什么。
  • *中有一篇 Trie 文章 - en.wikipedia.org/wiki/Trie#Algorithms,您可以在其中找到插入操作的伪代码。
  • @Kunal 是的,我需要使用扫描仪在其中添加单词,但我不知道该怎么做。

标签: java algorithm data-structures java.util.scanner trie


【解决方案1】:

有点不清楚data的目的是什么;您想将一些信息与每个存储的字符串相关联吗?基本上,添加一个新字符串意味着您从 trie 的根开始,然后按字符读取s 并在可能的情况下相应地遍历 trie 的弧。如果s的所有字符都在这个过程中被消耗掉了,你就完成了;如果有一些s 的后缀,你必须添加新的节点和弧来适应后缀。无论哪种情况,您都会到达一个节点,如果需要,您可以在其中存储data

【讨论】: