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/

上一篇:NOIP2014提高组题解


下一篇:$Noip2014/Luogu2296$ 寻找道路 图论