[LeetCode]Implement Trie(Prefix Tree),解题报告

目录

  • 目录
  • 概述
  • Trie树基本实现
    • 定义Trie树节点
    • 添加操作
    • 查询word是否在Trie树中
  • AC完整代码

概述

Trie树,又称为字典树、单词查找树或者前缀树,是一种用于快速检索的多叉数结构。例如,英文字母的字典树是26叉数,数字的字典树是10叉树。

Trie树的基本性质有三点,归纳为:

  1. 根节点不包含字符,根节点外每一个节点都只包含一个字符。
  2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  3. 每个节点的所有子节点包含的字符串不相同。

Trie树基本实现

我们通过LeetCode的上的一道Trie题目来描述Trie树的实现。Implement Trie(Prefix Tree)


定义Trie树节点

class TrieNode {
    boolean isWord;
    HashMap<Character, TrieNode> nexts;

    public TrieNode() {
        nexts = new HashMap<Character, TrieNode>();
    }
}

添加操作

我们向Trie树中添加一个字符串word,具体步骤如下:

    // Inserts a word into the trie.
    public void insert(String word) {
        char[] s = word.toCharArray();

        TrieNode p = root;
        int i = 0, n = s.length;

        // traverse existing
        while (i < n) {
            TrieNode next = p.nexts.get(s[i]);
            if (next != null) {
                p = next;
                i ++;
            } else {
                break;
            }
        }

        // append new nodes
        while (i < n) {
            TrieNode newTrie = new TrieNode();
            p.nexts.put(s[i], newTrie);
            p = newTrie;
            i ++;
        }

        // set word end
        p.isWord = true;
    }

查询word是否在Trie树中

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode p = root;

        for (int i = 0; i < word.length(); i ++) {
            TrieNode child = p.nexts.get(word.charAt(i));
            if (child == null) {
                return false;
            }
            p = child;
        }

        return p.isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode p = root;

        for (int i = 0; i < prefix.length(); i ++) {
            TrieNode child = p.nexts.get(prefix.charAt(i));
            if (child == null) {
                return false;
            }
            p = child;
        }

        return true;
    }

AC完整代码

import java.util.HashMap;

class TrieNode {
    boolean isWord;
    HashMap<Character, TrieNode> nexts;

    public TrieNode() {
        nexts = new HashMap<Character, TrieNode>();
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        char[] s = word.toCharArray();

        TrieNode p = root;
        int i = 0, n = s.length;

        // traverse existing
        while (i < n) {
            TrieNode next = p.nexts.get(s[i]);
            if (next != null) {
                p = next;
                i ++;
            } else {
                break;
            }
        }

        // append new nodes
        while (i < n) {
            TrieNode newTrie = new TrieNode();
            p.nexts.put(s[i], newTrie);
            p = newTrie;
            i ++;
        }

        // set word end
        p.isWord = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode p = root;

        for (int i = 0; i < word.length(); i ++) {
            TrieNode child = p.nexts.get(word.charAt(i));
            if (child == null) {
                return false;
            }
            p = child;
        }

        return p.isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode p = root;

        for (int i = 0; i < prefix.length(); i ++) {
            TrieNode child = p.nexts.get(prefix.charAt(i));
            if (child == null) {
                return false;
            }
            p = child;
        }

        return true;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("keydsdsds");
        System.out.println(trie.startsWith("key"));
    }
}
时间: 2024-10-14 05:23:52

[LeetCode]Implement Trie(Prefix Tree),解题报告的相关文章

leetcode Implement Trie (Prefix Tree)

题目连接 https://leetcode.com/problems/implement-trie-prefix-tree/ Implement Trie (Prefix Tree) Description Implement a trie with insert, search, and startsWith methods. 字典树.. class TrieNode { public: // Initialize your data structure here. bool vis; Tri

LeetCode——Implement Trie (Prefix Tree)

Description: Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. 实现一个简单的Trie树,参考我的博客:http://www.cnblogs.com/wxisme/p/4876197.html 1 class TrieNode { 2 public TrieNode

LeetCode Implement Trie (Prefix Tree) (实现trie树3个函数:插入,查找,前缀)

题意:实现trie树的3个功能,只含小写字母的串. 思路:老实做即可! 1 class TrieNode { 2 public: 3 TrieNode* chd[26]; 4 bool flag; 5 // Initialize your data structure here. 6 TrieNode() { 7 memset(chd,0,sizeof(chd)); 8 flag=0; 9 } 10 11 }; 12 13 class Trie { 14 public: 15 Trie() {

[LeetCode] Implement Trie (Prefix Tree) 实现字典树(前缀树)

Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. http://dongxicheng.org/structure/trietree/

[LeetCode][JavaScript]Implement Trie (Prefix Tree)

Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. https://leetcode.com/problems/implement-trie-prefix-tree/ 实现字典树,每个节点至多有26个子孙,代表26个字母. 每个节点都有三个属性,key, isWord以及字典(哈希表,提高访问速度,也可以用数组),因为JS可以扩展实例化的对象,直接用下标访问对象,不需

LeetCode 208. Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. 这道题让我们实现一个重要但又有些复杂的数据结构-字典树, 又称前缀树或单词查找树,详细介绍可以参见网友董的博客,例如,一个保存了8个键的trie结构,"A", "to", "tea&quo

Implement Trie (Prefix Tree) 解答

Question Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. Solution A trie node should contains the character, its children and the flag that marks if it is a leaf

Java for LeetCode 208 Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters a-z. 解题思路: 参考百度百科:Trie树 已经给出了详细的代码: JAVA实现如下: class TrieNode { // Initialize your data structure here. int num;// 有多少单

【LeetCode 208】Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. 思路: 构建一个简单的字典树,要求实现插入.查找.查找前缀三个操作.这里使用map实现对子树的构建(一方面方便查找,另一方面是懒 - -!),但是效率并不是太高,LeetCode上提交后跑了147ms,不是很理想,不过不影响对字