实现一个 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. 自定义Antd Pro 默认元素

    概要 通用元素 修改的方式 主页面 标签上的图标 logo 和 系统名称 footer 的配置 loading 页面 最终效果 概要 使用 Antd Pro 来开发前端项目时, 生成的项目模板中, 一 ...

  2. Android开发签名证书的生成

    现在都说互联网寒冬,其实只要自身技术能力够强,咱们就不怕!我这边专门针对Android开发工程师整理了一套[Android进阶学习视频].[全套Android面试秘籍].[Android知识点PDF] ...

  3. python xlrd读取Excel文件

    1 import xlrd 2 3 #打开excel文件 4 book = xlrd.open_workbook('salary.xls') 5 6 #打印每个工作表的名称 7 for sheet i ...

  4. python 爬取链家

    import json import requests from lxml import etree from time import sleep url = "https://sz.lia ...

  5. ASP.NET 获取客户端IP地址

    我们用Request.ServerVariables( "REMOTE_ADDR ")   来取得客户端的IP地址, 但如果客户端是使用代理服务器来访问,那取到的就是代理服务器的I ...

  6. Helium文档13-WebUI自动化-helium快速切换到selenium状态并调用其方法

    前言 前面说过helium是对Selenium 进行了封装,那么我们如何使用selenium的方法呢,通过下面的介绍,我们能够清楚在helium中能够使用selenium的任何方法 入参介绍 def ...

  7. tr命令-转换和删除字符

    tr 转换和删除字符 支持标准输入 格式 tr [OPTION]...SET1[SET2] Translate, squeeze, and/or delete characters from stan ...

  8. 2020年的UWP(2)——In Process App Service

    最早的时候App Service被定义为一种后台服务,类似于极简版的Windows Service.App Service作为Background Task在宿主UWP APP中运行,向其他UWP A ...

  9. B. Game of the Rows 解析(思維)

    Codeforce 839 B. Game of the Rows 解析(思維) 今天我們來看看CF839B 題目連結 題目 有如下圖片所示的飛機座位\(n\)排,和\(k\)隊士兵,每隊數量不一定. ...

  10. String字符串性能优化的探究

    一.背景 String 对象是我们使用最频繁的一个对象类型,但它的性能问题却是最容易被忽略的.String 对象作为 Java 语言中重要的数据类型,是内存中占用空间最大的一个对象,高效地使用字符串, ...