Trie 数据结构

定义

又称字典树、前缀树
图片说明

特性

1:根节点不包含字符,除了根节点外所有的每个节点仅包含一个字符
2:从根节点到某一个节点路径所经过的字符连接起来,即为该节点对应的字符串
3:任意节点的所有子节点所包含的字符不同。

use cases

1:自动补全
2:拼写检查
3:IP路由
4:词频统计

lc208

class Trie {

    /** Initialize your data structure here. */
    TrieNode root ;

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

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node =  root;
        for(char c : word.toCharArray()){
            if(node.children[c -'a'] == null){
                node.children[c -'a'] = new TrieNode();
            }
            node  = node.children[c - 'a'];
        }
        node.isWord = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = root;
        for(char c : word.toCharArray()){
            if(node.children[c - 'a'] ==null){
                return false;
            }
            else{
                node = node.children[c - 'a'];
            }
        }
        return node.isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for(char c: prefix.toCharArray()){
            if(node.children[c - 'a'] ==null){
                return false;
            }
           node = node.children[c - 'a'];
        }
        return true;
    }
}

class TrieNode{
        TrieNode[] children;
        boolean isWord;
        public TrieNode(){
            children = new TrieNode[26];
        }
    }
全部评论

相关推荐

07-09 18:28
门头沟学院 Java
写着提前批,结果还要实习4个月以上???
程序员牛肉:这种不用看,直接投了,面试的时候问对应的HR就行。有可能他们是直接复制的暑期实习的模板。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务