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");
        }
    }
     
    
  • 相关阅读:
    迭代器模式
    命令模式
    模板方法
    springmvc执行原理及自定义mvc框架
    代理模式
    外观模式
    组合模式
    装饰器模式
    02——Solr学习之Solr安装与配置(linux上的安装)
    01——Solr学习之全文检索服务系统的基础认识
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12947049.html
Copyright © 2011-2022 走看看