zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 208 实现 Trie (前缀树)

    
    public class FirstTrie {
        class Node{
            Node[] nodes;
            boolean isEnd;
            public Node(){
                nodes = new Node[26];
            }
        }
        private Node root;
     
        public FirstTrie(){
            root = new Node();
        }
        public void insert(String word){
            Node t = root;
            for(int i = 0;i < word.length();i++){
                int index = word.charAt(i)-'a';
                if(t.nodes[index] == null){
                    t.nodes[index] = new Node();
                }
                t = t.nodes[index];//跳到子节点
            }
            t.isEnd = true;
        }
        public boolean search(String word){
            Node t = root;
            for(int i = 0;i < word.length();i++){
                int index = word.charAt(i)-'a';
                if(t.nodes[index] == null){
                    return false;
                }
                t = t.nodes[index];//跳到子节点
            }
            return t.isEnd == true;
        }
     
        public boolean startsWith(String word){
            Node t = root;
            for(int i = 0;i < word.length();i++){
                int index = word.charAt(i)-'a';
                if(t.nodes[index] == null){
                    return false;
                }
                t = t.nodes[index];//跳到子节点
            }
            return true;
        }
     
        public static void main(String[] args) {
            FirstTrie m = new FirstTrie();
            m.insert("from");
            m.insert("tomorrow");
            m.insert("on");
            m.search("on");
            m.startsWith("o");
        }
    }
     
    
  • 相关阅读:
    百度翻译
    MailKit帮助类
    Ext.net 3.1学习
    求助 页面布局哪里错了
    jQuery 实现图片动画代码
    CSS图片水平垂直居中
    纯CSS选项卡
    百度纯CSS生成菜单
    KVM虚拟机配置
    快速部署Apache服务静态网站
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12947049.html
Copyright © 2011-2022 走看看