实现一个 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. CSS常见反爬技术

    目录 利用字体 反爬原理 应对措施 难点: 利用背景 反爬原理 应对措施 利用伪类 反爬原理 应对措施 利用元素定位 反爬原理 应对措施 利用字符切割 反爬原理 应对措施 利用字体 反爬原理 反爬原理 ...

  2. Mac 每次都要执行source ~/.bash_profile 后,配置的环境变量才生效

    问题: 自己在 ~/.bash_profile 中配置环境变量, 可是每次重启终端后配置的不生效.需要重新执行 : $source ~/.bash_profile后,才会生效. 原因: 自己是在bas ...

  3. 发布MeteoInfo 1.2.3

    提升了对GeoTiff格式数据的读取能力(多个tiles).当然还有MeteoInfoLab功能的提升.下载地址:http://yun.baidu.com/share/link?shareid=669 ...

  4. hdu6376 度度熊剪纸条-----01背包

    题目:度度熊有一张纸条和一把剪刀.   纸条上依次写着 N 个数字,数字只可能是 0 或者 1.     度度熊想在纸条上剪 K 刀(每一刀只能剪在数字和数字之间),这样就形成了 K+1 段.   他 ...

  5. Python基础数据类型及其转换

    数据类型: 浮点型float: 3.1415 也就是小数 整型 int: 123,主要用来运算,+-*/ 字符串 str: 'abc?', 记录少量信息 布尔值 bool: True or False ...

  6. 【机器学习 Azure Machine Learning】Azure Machine Learning 访问SQL Server 无法写入问题 (使用微软Python AML Core SDK)

    问题情形 使用Python SDK在连接到数据库后,连接数据库获取数据成功,但是在Pandas中用 to_sql 反写会数据库时候报错.错误信息为:ProgrammingError: ('42000' ...

  7. Linux文件元数据和节点表结构

    文件元数据 一块硬盘的分区可以认为有两部分组成,保存元数据的成为节点表,用来保存属性等. 元数据中有个小指针,指向数据存放的实际空间. 元数据(Metadata) 又称中介数据.中继数据,为描述数据的 ...

  8. django—模板相关

    关于在html文件中使用模板语言时,一些符号的含义 {{}}:显示变量相关,在模板渲染的时候替换成值 {%%}:处理逻辑相关 django模板语言中,对于列表字典等容器类型,不能够通过[ 索引/键值 ...

  9. 对于72种常用css3的使用经验

    对于72种常用css3的使用经验 保存网站源码 目的 保证有足够的css和js文件源码 拿到当前网页的整体布局 本地化 创建web项目 将web项目创建出来 在项目中创建一个文件夹 将所有的js和cs ...

  10. ps基本工具

    2.1PS移动工具 (1)快捷键:V. (2)多对象跨窗口移动的时候,按住键盘的shift再按鼠标左键拖拽可以快速定位到中心位置. (3)图层,一层层透明纸张叠加到一块的显示效果,每张透明的纸张上都有 ...