美文网首页
implement-trie-prefix-tree

implement-trie-prefix-tree

作者: 瞬铭 | 来源:发表于2020-02-06 17:38 被阅读0次

https://leetcode.com/problems/implement-trie-prefix-tree/
字典树的实现

image.png

talk is cheap ,直接上code

class Trie {
    
    public TrieNode root;

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

        public boolean isWord = false;
        TrieNode[] children;
    }

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        root = new TrieNode();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        TrieNode head = this.root;
        for (int i = 0; i < word.length(); i++) {
            char tmp = word.charAt(i);
            int idx = tmp - 'a';
            if (head.children[idx] == null) {
                head.children[idx] = new TrieNode();
            }
            head = head.children[idx];
        }
        head.isWord = true;
        return;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        TrieNode res = this.find(word);
        return res != null && res.isWord == true;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        TrieNode res = this.find(prefix);
        return res != null;
    }

    public TrieNode find(String word) {
        TrieNode head = this.root;
        for (int i = 0; i < word.length(); i++) {
            char tmp = word.charAt(i);
            int idx = tmp - 'a';
            if (head.children[idx] == null) {
                return null;
            }
            head = head.children[idx];
        }
        return head;
    }
}

参考链接:https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/

相关文章

网友评论

      本文标题:implement-trie-prefix-tree

      本文链接:https://www.haomeiwen.com/subject/nsyuxhtx.html