前缀树

前缀树

今天刷LeetCode看到了前缀树,于是我直接看(题解来自leetcode)。了解一下,记录一下。

208.前缀树

211. 添加与搜索单词 - 数据结构设计

Trie,又称前缀树或字典树(公共前缀子串树)

其每个节点包含一下字段:

  • 指向子节点的的指针数组children,对于208前缀树,children[0]对应小写a···children[25]对应小写z
  • isEnd:作为判断是否是单词的结尾
class TrieNode {
    boolean isEnd;//是否是单词的结尾
    TrieNode[] children;//26个小写字母

  	//构造
    public TrieNode() {
        isEnd = true;
        children = new TrieNode[26];

}

//插入单词

//插入字符串
    public void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            //判断字符有没有创建,如果没有创建就创建
            if (current.children[index] == null) {
                current.children[index] = new TrieNode();
                //中间的字符不是完整的单词
                current.children[index].isEnd = false;
            }
            current = current.children[index];
        }
        //最后一个字符才能构成一个完整的单词
        current.isEnd = true;
    }

924077AF-047E-41F9-8D7D-538EF116845D

插入字符串

  • 子节点存在。沿着指针移动到子节点,继续处理下一个字符。

  • 子节点不存在。创建一个新的子节点,记录在children[] 数组的对应位置上,然后沿着指针移动到子节点,继续搜索下一个字符。

private TrieNode find(String str) {
        TrieNode current = root;
        int length = str.length();
        for (int i = 0; i < length; i++) {
            int index = str.charAt(i) - 'a';
            if ((current = current.children[index]) == null)
                return null;
        }
        return current;
    }

public boolean search(String word) {
        TrieNode current = find(word);
        return current != null && current.isWord;
    }

查找字符串

  • 子节点存在。沿着指针移动到下一个节点,继续搜索下一个字符
  • 子节点不存在,说明字典树不包含该前缀,返回空指针

重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。

若搜索到了前缀的末尾,就说明字典树中存在该前缀。此外,若前缀末尾对应节点的 isEnd 为真,则说明字典树中存在该字符串。

原文地址:https://www.cnblogs.com/mankaixin/p/15429947.html