定义

又称字典树、前缀树
图片说明

特性

1:根节点不包含字符,除了根节点外所有的每个节点仅包含一个字符
2:从根节点到某一个节点路径所经过的字符连接起来,即为该节点对应的字符串
3:任意节点的所有子节点所包含的字符不同。

use cases

1:自动补全
2:拼写检查
3:IP路由
4:词频统计

lc208

class Trie {

    /** Initialize your data structure here. */
    TrieNode root ;

    public Trie() {
        root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node =  root;
        for(char c : word.toCharArray()){
            if(node.children[c -'a'] == null){
                node.children[c -'a'] = new TrieNode();
            }
            node  = node.children[c - 'a'];
        }
        node.isWord = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = root;
        for(char c : word.toCharArray()){
            if(node.children[c - 'a'] ==null){
                return false;
            }
            else{
                node = node.children[c - 'a'];
            }
        }
        return node.isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for(char c: prefix.toCharArray()){
            if(node.children[c - 'a'] ==null){
                return false;
            }
           node = node.children[c - 'a'];
        }
        return true;
    }
}

class TrieNode{
        TrieNode[] children;
        boolean isWord;
        public TrieNode(){
            children = new TrieNode[26];
        }
    }