前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode208. 实现 Trie (前缀树)

LeetCode208. 实现 Trie (前缀树)

作者头像
mathor
发布2018-08-17 15:41:57
6130
发布2018-08-17 15:41:57
举报
文章被收录于专栏:mathormathor
题目链接:[LeetCode208]()

 板子题,就不说了

代码语言:javascript
复制
class Trie {
    class TrieNode {
        public int end;
        public TrieNode[] nexts;
        public TrieNode() {
            end = 0;
            nexts = new TrieNode[26];
        }
    }
    TrieNode root = new TrieNode();
    
    /** Initialize your data structure here. */
    public Trie() {}
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if(word == null) 
                return;
        char[] chs = word.toCharArray();
        TrieNode node = root;
        int index = 0;
        for(int i = 0;i < chs.length;i++) {
            index = chs[i] - 'a';
            if(node.nexts[index] == null)
                node.nexts[index] = new TrieNode();
            node = node.nexts[index];
        }   
        node.end++;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        char chs[] = word.toCharArray();
        TrieNode node = root;
        int index = 0;
        for(int i = 0;i < chs.length;i++) {
            index = chs[i] - 'a';
            if(node.nexts[index] == null)
                return false;
            node = node.nexts[index];
        }
        return node.end > 0;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        char[] chs = prefix.toCharArray();
        TrieNode node = root;
        int index = 0;
        for(int i = 0;i < chs.length;i++) {
            index = chs[i] - 'a';
            if(node.nexts[index] == null)
                return false;
            node = node.nexts[index];
        }
        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);
 */
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接:[LeetCode208]()
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档