题目:

Implement a trie with insertsearch, and startsWith methods.

Example:

Trie trie = new Trie();

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

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

分析:

实现一个前缀树,包含insertsearch, and startsWith三个方法,分别对应插入,搜索单词和搜索前缀三个方法。

前缀树在这里就不多说了,网上的介绍有很多。

下面说一下具体的实现。

因为只有a-z共26个英文字母,所有开辟一个26大小的数组用来保存节点,isEnd用来表示该节点是否为单词终止节点,例如apple,那么在e节点时应该将isEnd置为true,以便搜索方法查询单词。

Trie* node[26] = {nullptr};
bool isEnd = false;

insert插入一个单词,遍历单词的每一个字符,从根节点开始查询对应位置的数组是否为空,如果为空就在对应位置新建节点,然后继续,在最后一个字符对应的位置isEnd记为true

void insert(string word) {
Trie* p = this;
for(const char ch:word){
if(p->node[ch-'a'] == nullptr)
p->node[ch-'a'] = new Trie();
p = p->node[ch-'a'];
}
p->isEnd = true;
}

search, and startsWith可以通过一个辅助函数来实现,遍历单词的字符,如果对应位置为null则表示前缀树中没有这个字符,返回null即可,否自返回查询到的最后一个结点。通过结点来判断单词是否存在,如果isEnd为true则search返回true。

Trie* mySearch(string word){
Trie *p = this;
for (auto c : word){
if (p->node[c - 'a'] == nullptr) return nullptr;
p = p->node[c - 'a'];
}
return p;
}

程序:

C++

class Trie {
public:
/** Initialize your data structure here. */
Trie() {
//root = new Trie();
} /** Inserts a word into the trie. */
void insert(string word) {
Trie* p = this;
for(const char ch:word){
if(p->node[ch-'a'] == nullptr)
p->node[ch-'a'] = new Trie();
p = p->node[ch-'a'];
}
p->isEnd = true;
} /** Returns if the word is in the trie. */
bool search(string word) {
Trie* res = mySearch(word);
return res && res->isEnd;
} /** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return mySearch(prefix) != nullptr;
}
private:
//Trie* root;
Trie* node[26] = {nullptr};
bool isEnd = false; Trie* mySearch(string word){
Trie *p = this;
for (auto c : word){
if (p->node[c - 'a'] == nullptr) return nullptr;
p = p->node[c - 'a'];
}
return p;
}
};

Java

class Trie {

    /** Initialize your data structure here. */
public Trie() { } /** Inserts a word into the trie. */
public void insert(String word) {
Trie p = this;
char[] w = word.toCharArray();
for(char ch:w){
if(p.node[ch - 'a'] == null)
p.node[ch - 'a'] = new Trie();
p = p.node[ch - 'a'];
}
p.isEnd = true;
} /** Returns if the word is in the trie. */
public boolean search(String word) {
Trie res = find(word);
return res != null && res.isEnd;
} /** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return find(prefix) != null;
} private Trie[] node = new Trie[26];
private boolean isEnd = false;
private Trie find(String word){
Trie p = this;
char[] w = word.toCharArray();
for(char ch:w){
if(p.node[ch - 'a'] == null)
return null;
p = p.node[ch - 'a'];
}
return p;
}
} /**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/

LeetCode 208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)(C++/Java)的更多相关文章

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

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

  2. Leetcode: Implement Trie (Prefix Tree) && Summary: Trie

    Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs a ...

  3. Leetcode208. Implement Trie (Prefix Tree)实现Trie(前缀树)

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

  4. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  5. [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  6. 【LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...

  7. 【刷题-LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...

  8. leetcode面试准备:Implement Trie (Prefix Tree)

    leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...

  9. LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design

    字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith  ...

  10. [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)

    Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...

随机推荐

  1. LORS:腾讯提出低秩残差结构,瘦身模型不掉点 | CVPR 2024

    深度学习模型通常堆叠大量结构和功能相同的结构,虽然有效,但会导致参数数量大幅增加,给实际应用带来了挑战.为了缓解这个问题,LORS(低秩残差结构)允许堆叠模块共享大部分参数,每个模块仅需要少量的唯一参 ...

  2. 【笔记】greatest/least函数&Round函数

    刷了一下力扣,发现有很多的函数是自己不清楚的,用了这些函数是比较容易得出结果的,不用自己费心去实现一些奇怪的东西 1.最大最小值 链接:https://leetcode.cn/problems/num ...

  3. 力扣239(Java)- 滑动窗口最大值(困难)

    题目: 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧.你只可以看到在滑动窗口内的 k 个数字.滑动窗口每次只向右移动一位. 返回 滑动窗口中的最大值 . 示 ...

  4. 力扣400(java)-第N位数字(中等)

    题目: 给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位上的数字. 示例 1: 输入:n = 3输出: ...

  5. 力扣319(java)-灯泡开关(中等)

    题目: 初始时有 n 个灯泡处于关闭状态.第一轮,你将会打开所有灯泡.接下来的第二轮,你将会每两个灯泡关闭第二个. 第三轮,你每三个灯泡就切换第三个灯泡的开关(即,打开变关闭,关闭变打开).第 i 轮 ...

  6. 第 9章 数据分析案例:Python 岗位行情

    第 9章 数据分析案例:Python 岗位行情 9.1 数据爬取 (1)打开某招聘网站首页 https://www.lagou.com,选择"全国站",在搜索栏输入 Python, ...

  7. 阿里云2020上云采购季,你最pick哪个产品组合?

    阿里云2020上云采购季如火如荼进行中,活动还剩最后10天啦,你的云产品都买好了吗? 还没买的,还没逛的,请戳:https://www.aliyun.com/sale-season/2020/proc ...

  8. 阿里云交互式分析与Presto对比分析及使用注意事项

    阿里云交互式分析与Presto对比分析及使用注意事项本文由阿里巴巴耿江涛带来以"阿里云交互式分析与Presto对比分析及使用注意事项"为题的演讲.文章首先介绍了Presto以及它的 ...

  9. 案例|自建or现成工具?小型创业团队敏捷研发探索

    简介: 实践和踩坑建议. 我是刘永良,是一名全栈开发者也是一名创业者,来自济南--一个目前被称为互联网洼地的地方.2020年4月和三位志同道合的朋友,在济南共同创建了山东旷野网络科技有限公司,主要从事 ...

  10. 11.Node节点维护

    题目:Node节点维护 配置环境kubectl config use-context ek8s 将名为ek8s-node-0的node节点设置为不可用,并重新调度该node上所有运行的pods. 官方 ...