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);
     */

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

  • 相关阅读:
    网络爬虫基础练习
    中文词频统计
    综合练习:英文词频统计
    字符串、组合数据类型练习
    MVC Controller进行单元测试
    mvc、webapi杂记
    C#异步执行
    cross-domain-ajax-request-jquery
    JS将/Date(1446704778000)/转换成string
    SQL并发数查询
  • 原文地址:https://www.cnblogs.com/doyi111/p/13127539.html
Copyright © 2011-2022 走看看