其他分享
首页 > 其他分享> > 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/

标签:Node,word,前缀,get,Trie,208,next,public,cur
来源: https://www.cnblogs.com/taoyuann/p/15535276.html