实现一个 Trie,包含 ​insert​, ​search​, 和 ​startsWith​ 这三个方法。
 
在线评测地址:领扣题库官网
 
 
样例 1:
输入: 
  insert("lintcode")
  search("lint")
  startsWith("lint")
输出: 
  false
  true
样例 2:
输入:
  insert("lintcode")
  search("code")
  startsWith("lint")
  startsWith("linterror")
  insert("linterror")
  search("lintcode”)
  startsWith("linterror")
输出: 
  false
  true
  false
  true
  true
 
题解
Trie(前缀树) 的模板应用.
 
// Version 1: Array of TrieNodeclass TrieNode {
    private TrieNode[] children;
    public boolean hasWord;
    
    public TrieNode() {
        children = new TrieNode[26];
        hasWord = false;
    }
    
    public void insert(String word, int index) {
        if (index == word.length()) {
            this.hasWord = true;
            return;
        }
        
        int pos = word.charAt(index) - 'a';
        if (children[pos] == null) {
            children[pos] = new TrieNode();
        }
        children[pos].insert(word, index + 1);
    }
    
    public TrieNode find(String word, int index) {
        if (index == word.length()) {
            return this;
        }
        
        int pos = word.charAt(index) - 'a';
        if (children[pos] == null) {
            return null;
        }
        return children[pos].find(word, index + 1);
    }
}
public class Trie {
    private TrieNode root;
 
    public Trie() {
        root = new TrieNode();
    }
 
    // Inserts a word into the trie.
    public void insert(String word) {
        root.insert(word, 0);
    }
 
    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode node = root.find(word, 0);
        return (node != null && node.hasWord);
    }
 
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode node = root.find(prefix, 0);
        return node != null;
    }
}
 
// Version 2: HashMap Version, this version will be TLE when you submit on LintCodeclass TrieNode {
    // Initialize your data structure here.
    char c;
    HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
    boolean hasWord;
    
    public TrieNode(){
        
    }
    
    public TrieNode(char c){
        this.c = c;
    }
}
public class Trie {
    private TrieNode root;
 
    public Trie() {
        root = new TrieNode();
    }
 
    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode cur = root;
        HashMap<Character, TrieNode> curChildren = root.children;
        char[] wordArray = word.toCharArray();
        for(int i = 0; i < wordArray.length; i++){
            char wc = wordArray[i];
            if(curChildren.containsKey(wc)){
                cur = curChildren.get(wc);
            } else {
                TrieNode newNode = new TrieNode(wc);
                curChildren.put(wc, newNode);
                cur = newNode;
            }
            curChildren = cur.children;
            if(i == wordArray.length - 1){
                cur.hasWord= true;
            }
        }
    }
 
    // Returns if the word is in the trie.
    public boolean search(String word) {
        if(searchWordNodePos(word) == null){
            return false;
        } else if(searchWordNodePos(word).hasWord) 
          return true;
          else return false;
    }
 
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if(searchWordNodePos(prefix) == null){
            return false;
        } else return true;
    }
    
    public TrieNode searchWordNodePos(String s){
        HashMap<Character, TrieNode> children = root.children;
        TrieNode cur = null;
        char[] sArray = s.toCharArray();
        for(int i = 0; i < sArray.length; i++){
            char c = sArray[i];
            if(children.containsKey(c)){
                cur = children.get(c);
                children = cur.children;
            } else{
                return null;
            }
        }
        return cur;
    }
}
 

[leetcode/lintcode 题解] 微软 面试题:实现 Trie(前缀树)的更多相关文章

  1. [leetcode/lintcode 题解] 微软面试题:股票价格跨度

    编写一个 StockSpanner 类,它收集某些股票的每日报价,并返回该股票当日价格的跨度. 今天股票价格的跨度被定义为股票价格小于或等于今天价格的最大连续日数(从今天开始往回数,包括今天). 例如 ...

  2. [leetcode/lintcode 题解] 微软面试题:公平索引

    现在给你两个长度均为N的整数数组 A 和 B. 当(A[0]+...A[K-1]),(A[K]+...+A[N-1]),(B[0]+...+B[K-1]) 和 (B[K]+...+B[N-1])四个和 ...

  3. [leetcode/lintcode 题解] Amazon面试题:连接棒材的最低费用

    为了装修新房,你需要加工一些长度为正整数的棒材 sticks. 如果要将长度分别为 X 和 Y 的两根棒材连接在一起,你需要支付 X + Y 的费用. 由于施工需要,你必须将所有棒材连接成一根. 返回 ...

  4. [leetcode/lintcode 题解] 谷歌面试题:找出有向图中的弱连通分量

    请找出有向图中弱连通分量.图中的每个节点包含 1 个标签和1 个相邻节点列表.(有向图的弱连通分量是任意两点均有有向边相连的极大子图) 将连通分量内的元素升序排列. 在线评测地址:https://ww ...

  5. [leetcode/lintcode 题解] Google面试题:合法组合

    给一个单词s,和一个字符串集合str.这个单词每次去掉一个字母,直到剩下最后一个字母.求验证是否存在一种删除的顺序,这个顺序下所有的单词都在str中.例如单词是’abc’,字符串集合是{‘a’,’ab ...

  6. [leetcode/lintcode 题解] 前序遍历和中序遍历树构造二叉树

    [题目描述] 根据前序遍历和中序遍历树构造二叉树. 在线评测地址: https://www.jiuzhang.com/solution/construct-binary-tree-from-preor ...

  7. 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...

  8. 第15个算法-实现 Trie (前缀树)(LeetCode)

    解法代码来源 :https://blog.csdn.net/whdAlive/article/details/81084793 算法来源:力扣(LeetCode)链接:https://leetcode ...

  9. leetcode 208. 实现 Trie (前缀树)

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作. 示例: Trie trie = new Trie(); trie.insert(" ...

随机推荐

  1. 多测试讲解_009肖sirRF自动化框架安装教程

    robot framework:自动化测试框架 Python3.7 RIDE(可视化界面).  Wxpython  pip(在线下载) . setuptools(在线安装) . 第三方库 第三方库:s ...

  2. 骨架屏(page-skeleton-webpack-plugin)初探

    作者:小土豆biubiubiu 博客园:https://www.cnblogs.com/HouJiao/ 掘金:https://juejin.im/user/2436173500265335 微信公众 ...

  3. Anderson《空气动力学基础》5th读书笔记 第3记——流动类型

    一.连续介质与自由分子流动   分子之间相互碰撞的平均距离定义为平均自由程 .如果平均自由程的数量级远小于飞行器的尺寸时,此时,分子对物体的碰撞如此频繁以至于物体无法分辨出单个的分子碰撞,这时,对物体 ...

  4. docker compose 用法

    目录 docker compose的使用场景 一个基本的demo演示 找一个目录,在其中创建一个python文件app.py 在相同的文件夹下,创建requirements.txt文件 在相同的文件夹 ...

  5. 通过Relect反射方法创建对象,获得对象的方法,输出对象信息

    package reflects; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java. ...

  6. JS-根据身份证获取 出生日期和性别

    一.根据身份证获取出生日期和性别/** * 根据身份证获取出生日期(yyyy-MM-dd) * @param psidno * @returns {birthday:yyyy-MM-dd} * @co ...

  7. eclipse配置springMVC

    基础还是创建一个Dynamic web project. WEB-INF/lib中添加必需的jar. commons-logging-1.1.3.jar spring-aop-4.3.6.RELEAS ...

  8. ArcPy批量选择指定属性的要素

    在GIS数据处理中,选择数据是十分频繁的操作,常用的是"按属性选择"和"按位置选择",这两个功能虽然比较强大,但有时也不能满足实际需求.比如可能时常会遇到这样一 ...

  9. Luogu P4643 阿狸和桃子的游戏

    题解 传送门 既然题目要求的是差值 所以对于减数和被减数同时加上一个相同的数是毫无影响的 (详情参考人教版六年级上册数学教材) 所以不妨把边权分成两半 分别加给两个顶点 然后,直接每次选最大的点就好了 ...

  10. STM32入门系列-STM32外设地址映射

    片上外设区分为四条总线,根据外设速度的不同,不同总线挂载着不同的外设,APB1挂载低速外设,APB2和AHB挂载高速外设.相应总线的最低地址我们称为该总线的基地址,总线基地址也是挂载在该总线上的首个外 ...