1. 程式人生 > 其它 >208. 實現Trie(字首樹)

208. 實現Trie(字首樹)

import java.util.TreeMap;

class Trie {

    class Node{

        boolean isWord;
        TreeMap<Character, Node> next;

        public Node(){

            next = new TreeMap<>();
            isWord = false;
        }
    }

    Node root;
    int size;

    public Trie() {

        root = new Node();
        size = 0;
    }

    public void insert(String word) {

        Node cur = root;

        for (int i = 0; i < word.length(); i++) {

            char c = word.charAt(i);

            if (cur.next.get(c) == null){
                cur.next.put(c, new Node());
            }

            cur = cur.next.get(c);
        }

        if (!cur.isWord) {

            cur.isWord = true;
            size++;
        }
    }

    public boolean search(String word) {

        Node cur = root;

        for (int i = 0; i < word.length(); i++) {

            char c = word.charAt(i);

            if (cur.next.get(c) == null){
                return false;
            }
            else {
                cur = cur.next.get(c);
            }
        }

        return cur.isWord;
    }

    public boolean startsWith(String prefix) {

        Node cur = root;

        for (int i = 0; i < prefix.length(); i++) {

            char c =prefix.charAt(i);
            
            if (cur.next.get(c) == null){
                return false;
            }
            else {
                cur = cur.next.get(c);
            }
        }

        return true;
    }
}

https://leetcode-cn.com/problems/implement-trie-prefix-tree/