【问题标题】:Java: Storing Substrings in a TrieJava:在 Trie 中存储子字符串
【发布时间】:2012-10-28 21:25:33
【问题描述】:

我正在实现一个 trie,它将同时存储子字符串及其在字符串中的出现次数。我的 trie 中的每个节点都会有一个名为 children 的 Map,它将存储主节点的所有子节点。

我的问题是,最终,这些子节点将拥有自己的子节点,我不知道如何从“地图中的地图中的地图......”可以这么说。

这是我目前所拥有的:

private class TrieNode
{
    private T data; //will hold the substring
    int count; //how many occurrences of it were in the string
    private Map<TrieNode, Integer> children; //will hold subnodes
    private boolean isWord; //marks the end of a word if a substring is the last substring of a String

    private TrieNode(T data)
    {
        this.data = data;
        count = 1;
        children = new HashMap<TrieNode, Integer>();
        isWord = false;
    }
} 

如何从子节点中检索数据,这些子节点下可能有其他子节点?

附:如果我无法足够清楚地解释它,我深表歉意 - 我遇到了递归问题。谢谢。

【问题讨论】:

    标签: java string recursion trie


    【解决方案1】:

    我不明白为什么要将字符串存储在名为 T 的类型中。这听起来像是泛型类型,但你没有在类中声明它。

    无论如何,我认为您需要一个 Map&lt;T, TrieNode&gt; 来保存由其子字符串键入的每个子项。这样您就可以再次访问另一个TrieNode,它又拥有另一张相同类型的地图。

    【讨论】:

    • 为了这篇文章——为了更容易理解——我说它是一个字符串,但它确实是一个泛型类型。顺便说一句,这个节点类是另一个名为“Trie”的类中的私有类。我在其标题中声明了 T。
    【解决方案2】:

    你需要一些东西。首先,您需要Map&lt;T, TrieNode&gt;,因为您正在将一条数据映射到一个子Trie。

    其次,您需要知道如何将数据拆分为头部和尾部,以及以后如何重新组合它们。在字符串的标准情况下,您使用子字符串和连接。例如:

    private TrieNode(String currChar, String rest) {
       this.data = currChar;
       this.children = new HashMap<String, TrieNode>();
       if(rest.isEmpty()) {
          this.isWord = true;
       } else {
          String head = rest.substring(0, 1);
          String tail = rest.substring(1, rest.length());
          this.children.add(head, new TrieNode(head, tail);
       }
    }
    

    您的T 需要能够做类似的事情,或者首先使用 Trie 没有意义。

    此外,您很少需要从 Trie 重新编译字符串。通常,您只是检查一个字符串是否存在于 Trie 中,或者某个字符串是多少个字符串的子字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      相关资源
      最近更新 更多