Leetcode 208:实现Trie(前缀树)

Leetcode 208:实现Trie(前缀树)

题目描述

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // 返回 true
trie.search("app");     // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");   
trie.search("app");     // 返回 true

说明:

你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。

思路

思路1: 前缀树基本实现

主要是使用前缀树的基本概念,将前缀字母连接到下一个后缀节点,以及标记好结束节点

代码

思路1代码

class Trie {
    private final int alphaSize = 26;
    private Trie[] children = new Trie[alphaSize];
    private boolean isEnd = false;

    /** Initialize your data structure here. */
    public Trie() {

    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie temp = this;
        for(var ch: word.toCharArray()){
            if (temp.children[ch - 'a'] == null){
                temp.children[ch - 'a'] = new Trie();
            }
            temp = temp.children[ch - 'a'];
        }
        temp.isEnd=true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie temp = this;
        for(var ch: word.toCharArray()){
            if (temp.children[ch - 'a'] == null){
                return false;
            }
            temp = temp.children[ch - 'a'];
        }
        return temp.isEnd;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie temp = this;
        for(var ch: prefix.toCharArray()){
            if (temp.children[ch - 'a'] == null){
                return false;
            }
            temp = temp.children[ch - 'a'];
        }
        return true;
    }
}

复杂度分析

时间复杂度

$n$均可看作是链表的查找插入

空间复杂度

$n$


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode 212: 单词搜索II Leetcode 212: 单词搜索II
Leetcode 212: 单词搜索II题目描述给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相
2020-03-21
下一篇 
Leetcode 140: 单词切分II Leetcode 140: 单词切分II
Leetcode 140: 单词切分II题目描述给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。 说明:分隔时可以重复使用字
2020-03-19
  目录