大厂面试真题详解:实现 Trie(前缀树)

简介: 大厂面试真题详解:实现 Trie(前缀树)

实现一个 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(前缀树) 的模板应用.
维基百科: https://zh.wikipedia.org/zh-hans/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;
    }
}

更多题解参考:九章官网solution

相关文章
|
存储 算法 C++
【每日算法Day 84】面试必考题:Trie(字典树/前缀树)的实现
【每日算法Day 84】面试必考题:Trie(字典树/前缀树)的实现
|
Serverless C语言 索引
华为面试C语言真题(二)
华为面试C语言真题( 二)
291 1
华为面试C语言真题(二)
|
安全 测试技术 Python
软件测试面试题及答案,这个题库有3千多道最新面试真题可以刷
相信对于很多软件测试新手来说,技术项目的面试是十分让人头疼的,生怕没回答得好,就会跟这个offer失之交臂
191 0
|
设计模式 缓存 算法
腾讯Java高级岗180道面试真题,面试大厂拿45Koffer没问题!
一、数据结构与算法基础 · 说一下几种常见的排序算法和分别的复杂度。 · 用Java写一个冒泡排序算法 · 描述一下链式存储结构。 · 如何遍历一棵二叉树? · 倒排一个LinkedList。 · 用Java写一个递归遍历目录下面的所有文件
|
消息中间件 NoSQL 网络协议
字节跳动三面Java经历,砍下年薪50W的Offer,面试真题整理分享
应广大读者要求,今天开更一些大厂的面经和相关的面试干货,下面这份**最新字节跳动春招面经+笔记**带给大家。
143 0
字节跳动三面Java经历,砍下年薪50W的Offer,面试真题整理分享
|
NoSQL 算法 Dubbo
Java工程师丨面试真题(二)
Java工程师丨面试真题(二)
Java工程师丨面试真题(二)
Java工程师丨面试真题(一)
Java工程师丨面试真题(一)
|
存储 自然语言处理 前端开发
【牛客刷题】大厂真题 | 前端面试篇(一)
【牛客刷题】大厂真题 | 前端面试篇(一)
189 0
|
人工智能 Java 测试技术
【牛客刷题系列】Java工程师 | 百度面试真题(二)
【牛客刷题系列】Java工程师 | 百度面试真题(二)
117 0