【前缀树】哈希表和字符数组两种实现

一、什么是前缀树

前缀树 Trie ,又称为字典树, 是一种树形数据结构,用于高效地 存储和检索字符串数据集中的键 。这一数据结构有相当多的应用情景,例如 自动补完和拼写检查

其结构如下图所示 ,其模拟了将如下字符串插入前缀树的过程 :

[apple, app, ap, ba, baidu]


二、前缀树代码实现

  1. 使用 Trie[] 实现, 利用小写字符和数组下标的关系
class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

  1. 使用 HashMap<Character, Trie> 实现,直接存储字符本身
public class Trie {
    Map<Character, Trie> children; // 孩子节点
    boolean isEnd; // 结束标志
    public Trie() {
        children = new HashMap<>();
        isEnd = false;
    }

    public void insert(String word) {
        Trie node = this; // 得到根节点
        for(Character cur : word.toCharArray()){ // 遍历 word
            if(!node.children.containsKey(cur)){ // 加入前缀树中
                node.children.put(cur, new Trie());
            }
            node = node.children.get(cur);
        }
        node.isEnd = true; // 标志结束
    }

    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }

    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    // 找到以 prefix 为前缀的前缀树节点,不存在返回 null
    public Trie searchPrefix(String prefix) {
        Trie node = this;
        for(Character cur : prefix.toCharArray()){
            if(!node.children.containsKey(cur)){ // 不含当前前缀
                return null;
            }
            node = node.children.get(cur);
        }
        return node;
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值