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

    开始想到了用前缀树,但是没写出来

    class Trie {
    
        class TireNode {
            private boolean isEnd;
            TireNode[] next;
    
            public TireNode() {
                isEnd = false;
                next = new TireNode[26];
            }
        }
    
        private TireNode root;
    
        public Trie() {
            root = new TireNode();
        }
    
        public void insert(String word) {
            TireNode node = root;
            for (char c : word.toCharArray()) {
                if (node.next[c - 'a'] == null) {
                    node.next[c - 'a'] = new TireNode();
                }
                node = node.next[c - 'a'];
            }
            node.isEnd = true;
        }
    
        public boolean search(String word) {
            TireNode node = root;
            for (char c : word.toCharArray()) {
                node = node.next[c - 'a'];
                if (node == null) {
                    return false;
                }
            }
            return node.isEnd;
        }
    
        public boolean startsWith(String prefix) {
            TireNode node = root;
            for (char c : prefix.toCharArray()) {
                node = node.next[c - 'a'];
                if (node == null) {
                    return false;
                }
            }
            return true;
        }
    }
    
    /**
     * Your Trie object will be instantiated and called as such:
     * Trie obj = new Trie();
     * obj.insert(word);
     * boolean param_2 = obj.search(word);
     * boolean param_3 = obj.startsWith(prefix);
     */

    唔 好久没来了  要继续加油啊 奥里给

  • 相关阅读:
    react脚手架
    快速创建一个node后台管理系统
    vue脚手架结构及vue-router路由配置
    Spring 事务管理-只记录xml部分
    Spring-aspectJ
    Maven 自定义Maven插件
    JVM
    JVM
    Spring
    Digester
  • 原文地址:https://www.cnblogs.com/doyi111/p/13127539.html
Copyright © 2011-2022 走看看