字母前缀树

1 阅读1分钟

208. 实现 Trie (前缀树) - 力扣(LeetCode)

边为cnt,26个字母为方向,点是cnt 结构体要用起来,你的老方法是固定分配内存数组,构造类才方便动态分配

class Trie {
    
    // 思路对的,但是结构体要用起来,你的老方法是固定分配内存数组,构造类才方便动态分配
    private static class Node {
        Node[] son = new Node[26];
        boolean end = false;
    }

    private final Node root = new Node();

    public Trie() {
        
    }
    
    public void insert(String word) {
        Node cur = root;
        for(char c : word.toCharArray()) {
            c -= 'a';
            if (cur.son[c] == null) { // 无路了
                cur.son[c] = new Node();
            }
            cur = cur.son[c];
        }
        cur.end = true;
        
    }
    
    public boolean search(String word) {
        return find(word) == 2;
    }
    
    public boolean startsWith(String prefix) {
        return find(prefix) != 0;
    }

    private int find(String word) {
        Node cur = root;
        for (char c : word.toCharArray()) {
            c -= 'a';
            if (cur.son[c] == null) {
                return 0;
            }
            cur = cur.son[c];
        }

        return cur.end ? 2 : 1;
    }
}

/**
 * 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);
 */