码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-15 00:02:15      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:前缀树   efi   void   next   ant   ret   tar   OLE   code   

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

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 (前缀树)

标签:前缀树   efi   void   next   ant   ret   tar   OLE   code   

原文地址:https://www.cnblogs.com/doyi111/p/13127539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!