implement-trie-prefix-tree

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/

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容