Trie(字典树、前缀树)数据结构

前缀树是一种非典的的多叉树,多叉树好理解就是多个分支,非典型则是指前缀树的节点的数据结构与一般的树不同。

先上代码,再讲我的理解(对应于LeetCode 208

class Trie {
    private Node root;

    public Trie() {
        root = new Node();
    }
    
    public void insert(String word) {
        Node tmp = root; 
        int pos = -1;
        for (char ch : word.toCharArray()){
            pos = ch - 'a'; //计算位置
            if (tmp.next[pos] == null){ //如果该字母不存在
                tmp.next[pos] = new Node();//则添加
            }
            tmp = tmp.next[pos];
        }
        tmp.isEnd = true;//别忘了,一个单词结束要标记为true
    }
    
    public boolean search(String word) {
        Node tmp = root;
        int pos = -1;
        for (char ch : word.toCharArray()){
            pos = ch - 'a';
            if (tmp.next[pos] == null)
                return false;
            tmp = tmp.next[pos];
        }
        return tmp.isEnd;//判断是否是一个完整的单词
    }
    
    public boolean startsWith(String prefix) {
        Node tmp = root;
        int pos = -1;
        for (char ch : prefix.toCharArray()){
            pos = ch - 'a';
            if (tmp.next[pos] == null)
                return false;
            tmp = tmp.next[pos];
        }
        return true;//与search的区别,只要能匹配上即可,无需关注是否为一个单词
    }
    
}
class Node{
    //为了简便处理,属性就设置为public了
    public boolean isEnd;
    public Node[] next;

    public Node(){
        isEnd = false;
        next = new Node[26];
    }
}

首先,观察一下字典树中Node的数据结构

class Node{
    //为了简便处理,属性就设置为public了
    public boolean isEnd;
    public Node[] next;

    public Node(){
        isEnd = false;
        next = new Node[26];
    }
}

再看看一般多叉树的数据结构

class Node{
    int value; //节点值
    Node[] next; //所有孩子节点

    public Node(){}
}
  • 多叉树的节点保存的是当前节点的值以及其指向其所有孩子节点指针
  • 字典树的节点保存的当前节点是否为某个单词的最后一个字母;理解字典树最重要的一点就是理解next数组,Node[] next = new Node[26], 数组下标对应于下一个字母是什么,例如,'a’对应于next[0],'b’对应于next[1]…依次类推,也就是说在字典树中用位置表示值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值