字典树

  1. 字典树

字典树

又称前缀树,实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

public class T208Trie {
    class TrieNode{
        TrieNode []nodes;
        boolean isLeaf;
        int id;
        public TrieNode(){
            nodes=new TrieNode[26];
            isLeaf=false;
            id=0;
        }
    }
    private TrieNode root;
    public T208Trie() {
        root=new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode tmpRoot=root;
        int len=word.length();
        for (int i = 0; i < len; i++) &#123;
            char c=word.charAt(i);
            if(tmpRoot.nodes[c-'a']==null)&#123;
                tmpRoot.nodes[c-'a']=new TrieNode();
            &#125;
            tmpRoot=tmpRoot.nodes[c-'a'];
        &#125;
        tmpRoot.isLeaf=true;
    &#125;

    /** Returns if the word is in the trie. */
    public boolean search(String word) &#123;
        TrieNode tmpRoot=root;
        int len=word.length();
        for (int i = 0; i < len; i++) &#123;
            char c=word.charAt(i);
            if(tmpRoot.nodes[c-'a']==null)return false;
            tmpRoot=tmpRoot.nodes[c-'a'];
        &#125;
        return tmpRoot.isLeaf;
    &#125;

    public boolean startsWith(String prefix) &#123;
        TrieNode tmpRoot=root;
        int len=prefix.length();
        for (int i = 0; i < len; i++) &#123;
            char c=prefix.charAt(i);
            if(tmpRoot.nodes[c-'a']==null)return false;
            tmpRoot=tmpRoot.nodes[c-'a'];
        &#125;
        return true;
    &#125;

    public static void main(String[] args) &#123;
        T208Trie t208Trie=new T208Trie();
        t208Trie.insert("hello");
        System.out.println(t208Trie.search("hell")); // false
        System.out.println(t208Trie.search("helloa")); // false
    &#125;
&#125;

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 changzeyan@foxmail.com

×

喜欢就点赞,疼爱就打赏