🌕 208. 实现 Trie (前猀树)

吞䜛童子2022幎10月10日
  • algorithm
  • tree
  • 倚叉树
倧纊 1 分钟

🌕 208. 实现 Trie (前猀树)

隟床: 🌕

问题描述

img_5.png


解法

class Trie {
    // 思路
    // 䞀共 26 䞪小写字母所以构造 26 叉树
    Node root;

    public Trie() {
        this.root = new Node('a'); // 初始化根节点查扟元玠时从根节点的孩子匀始䜜䞺銖字母
    }
    
    public void insert(String word) {
        int len = word.length();
        Node cur = root;
        for(int i = 0; i < len; i ++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                cur.child[index] = new Node(c);
            }
            cur = cur.child[index];
        }
        cur.end = true; // 标记是某䞪单词的最后䞀䞪字笊所圚的节点
    }
    
    public boolean search(String word) {
        // 查扟 完党匹配单词 - 需芁到蟟叶子节点
        Node cur = root;
        int len = word.length();
        for(int i = 0; i < len; i ++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                return false;
            } 
            cur = cur.child[index];
        }
        // 需芁保证 cur 没有任䜕子节点
        return cur.end;
    }
    
    public boolean startsWith(String prefix) {
        // 查扟 前猀单词 - 䞍需芁到蟟叶子节点
        Node cur = root;
        int len = prefix.length();
        for(int i = 0; i < len; i ++) {
            char c = prefix.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                return false;
            } 
            cur = cur.child[index];
        }
        return true;
    }
}

// 构造 26 叉树 节点类
class Node {
    char val;
    boolean end;
    Node[] child;
    public Node(char val) {
        this.val = val;
        this.end = false; // 标记该节点是吊䞺单词的最后䞀䞪节点
        this.child = new Node[26];
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

蟓出

img_4.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou