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");
        }
    }
     
    
  • 相关阅读:
    bootstrapValidator重新校验/全选回显
    mybatis遍历map参数查询
    location.href传json字符串
    springmvc异步处理
    intellIJ IDEA学习笔记3
    intellIJ IDEA学习笔记2
    intellIJ IDEA学习笔记
    maven国内镜像
    Docker版本Jenkins的使用
    Docker容器网络
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12947049.html
Copyright © 2011-2022 走看看