前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >字典书Trie的实现

字典书Trie的实现

作者头像
用户2436820
发布2019-04-09 15:01:34
5180
发布2019-04-09 15:01:34
举报

身为程序员,需要弄懂Trie(字典书的实现) 具体应用场景和讲解-请一定要看 提供的API如下

  • insert(String world) 向字典中插入
  • search(String world) 字典中查询此字符串
  • startWith(String world) 查询字典中的公有开头
代码语言:javascript
复制
class TrieNode {
    private TrieNode[] links;
    private final int R = 26;
    private boolean isEnd;
    private TrieNode root;
    public TrieNode(){
        this.links = new TrieNode();
    }
    public boolean containKeys(char c){
        return links[c-'a']!=null;
    }
    public void put(char c,TrieNode node){
        links[c-'a']=node;
    }
    public void setEnd(){
        this.isEnd = true;
    }
    public boolean isEnd(){
        return isEnd;
    }
    public TrieNode get(char c){
        return links[c-'a'];
    }
    public void insert(String world){
        TrieNode node = root;
        for (int i = 0; i < world.length(); i++) {
            char currentChar = world.charAt(i);
            if(!node.containKeys(currentChar)){
                node.put(currentChar, new TrieNode());
            }
            node = node.get(currentChar);
        }
        node.setEnd();
    }
    public boolean search(String world){
        TrieNode node = searchPrex(world);
        return node!=null && node.isEnd();
    }
    public boolean startWith(String world){
        TrieNode node = searchPrex(world);
        return node!=null;
    }
    public TrieNode searchPrex(String world){
        TrieNode node = root;
        for (int i = 0; i < world.length(); i++) {
            char currentChar = world.charAt(i);
            if(node.containKeys(c))node = node.get(currentChar);
            else return null;
        }
        return node;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.03.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档