208. 实现 Trie (前缀树)

258 阅读1分钟

image.png

Solution: Using HashMap

image.png

  • Insertion:
    • O(m), O(m) in worst case(we need to insert a total new str)
  • Serach:
    • O(m) o(1)
class Trie {
    // Define Trie Node
    class Node {
        Map<Character, Node> children = new HashMap<>();
        boolean isEnd;
        Node() {}
    }

    // root不存数据
    Node root;
    public Trie() {
        root = new Node();
    }
    
    public void insert(String word) {
        Node cur = root;
        for (char c : word.toCharArray()) {
            if (!cur.children.containsKey(c)) { // new char
                cur.children.put(c, new Node());
            }
            cur = cur.children.get(c); // points to next level node
        }

        cur.isEnd = true;// end of word
    }
    
    public boolean search(String word) {
        Node cur = root;
        for (char c : word.toCharArray()) {
            if (!cur.children.containsKey(c)) {
                return false;
            }
            cur = cur.children.get(c);
        }
        return cur.isEnd; // whole word match
    }
    
    public boolean startsWith(String prefix) {
        Node cur = root;
        for (char c : prefix.toCharArray()) {
            if (!cur.children.containsKey(c)) {
                return false;
            }
            cur = cur.children.get(c);
        }
        return true;
    }
}

Solution: using array

  • 包含三个单词 "sea","sells","she" 的 Trie

image.png

class Trie {
    public Node root;//根节点

    public class Node {
        public Node[] children;
        public boolean isEnd;//当前节点为叶子?
        public Node() {
            children = new Node[26];
        }
    }

    public Trie() {
        root = new Node();
    }
    // 插入
    // root is null不存数据
    public void insert(String word) {
        Node node = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (node.children[index] == null) {//插入新的字符
                node.children[index] = new Node();//在对应的index上新建节点
            }
            node = node.children[index];//指针移动
        }
        node.isEnd = true;
    }
    // 搜索
    public boolean search(String word) {
        Node node = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (node.children[index] == null) {
                return false;
            }
            node = node.children[index];
        }
        return node.isEnd;
    }
    // 判断prefix
    public boolean startsWith(String prefix) {
        Node node = root;
        for (int i = 0; i < prefix.length(); i++) {
            int index = prefix.charAt(i) - 'a';
            if (node.children[index] == null) {
                return false;
            }
            node = node.children[index];
        }
        return true;
    }
}