【问题标题】:Search word in Trie?在 Trie 中搜索单词?
【发布时间】:2016-05-04 08:04:32
【问题描述】:

我有一个 Java 的 Trie,我想搜索是否包含一个单词。

例如:Trie: [casa-perro-animal], hogar = false;卡萨=真;

public boolean search (String word){
    /**Method to complete**/
}

还有带节点的 Trie 类:

public class Trie {
/**
 * Clase auxiliar para guardar caracteres que forman parte de una palabra
 * @author zenon
 */
protected class Info {
    char c;    // Caracter actual
    Info alt;  // Caracter alternativo para la misma posición
    Info next; // Caracter que es la primera opción en la siguiente posición

    public Info(char c, Info alt, Info next) {
        this.c = c;
        this.alt = alt;
        this.next = next;
    }
}

protected Info root; // Referencia al punto de inicio de la estructura

有什么帮助吗?我是西班牙人。非常感谢。

【问题讨论】:

  • 使用包含String类的方法
  • 没有使用 contains 方法,创建我自己的方法。
  • 如果您尝试自己解决问题,而不是要求别人为您做作业,您将从编程课中获得更多收益。

标签: java trie


【解决方案1】:

您正在查看 Trie 的 doubly chained tree 实现:
image and description from wikipedia's entry on Trie

垂直箭头是子指针,水平虚线箭头是下一个指针。存储在这个 trie 中的字符串集是{baby, bad, bank, box, dad, dance}。列表被排序以允许按字典顺序遍历


如何搜索

您的搜索必须对搜索到的word 中的字符一一进行处理并导航。

取第一个字符并检查您的根是否包含它。如果是,您可以移动到 word 中的下一个字符,然后沿着实心箭头向下移动到当前 list 的下一个节点 - 在您的实现中,它是 next 类型的 Info 节点.这样您就可以在同一个 list 中向下遍历(根据上图)。

如果当前节点不包含您正在搜索的字符,您将水平移动到下一个替代列表(沿虚线)。在您的情况下,这由 alt Info 节点表示。然后你在那里对同一个字母重复测试。如果运气不好,请再次移至下一个替代列表。

如果您在给定级别检查了所有替代 列表 没有任何匹配,并且面临死胡同(其中alt == null),您可以得出结论word 不包含在其中你的尝试。

相反,如果您已使用来自word 的所有字符并且位于列表 中的最后一个节点(即next == null),那么您可以断定word 存储在其中尝试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多