[LeetCode] 208. 实现 Trie (前缀树)

Posted 怕什么

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 208. 实现 Trie (前缀树)相关的知识,希望对你有一定的参考价值。

开始想到了用前缀树,但是没写出来

class Trie {

    class TireNode {
        private boolean isEnd;
        TireNode[] next;

        public TireNode() {
            isEnd = false;
            next = new TireNode[26];
        }
    }

    private TireNode root;

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

    public void insert(String word) {
        TireNode node = root;
        for (char c : word.toCharArray()) {
            if (node.next[c - ‘a‘] == null) {
                node.next[c - ‘a‘] = new TireNode();
            }
            node = node.next[c - ‘a‘];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        TireNode node = root;
        for (char c : word.toCharArray()) {
            node = node.next[c - ‘a‘];
            if (node == null) {
                return false;
            }
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        TireNode node = root;
        for (char c : prefix.toCharArray()) {
            node = node.next[c - ‘a‘];
            if (node == null) {
                return false;
            }
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

唔 好久没来了  要继续加油啊 奥里给

 

以上是关于[LeetCode] 208. 实现 Trie (前缀树)的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]208. 实现 Trie (前缀树)

leetcode 208. 实现 Trie (前缀树)

leetcode 208. 实现 Trie (前缀树)/字典树

[LeetCode] 208. 实现 Trie (前缀树)

leetcode中等208实现 Trie (前缀树)

leetcode中等208实现 Trie (前缀树)