题目:

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. 力扣71(java)-简化路径(中等)

    题目: 给你一个字符串 path ,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 '/' 开头),请你将其转化为更加简洁的规范路径. 在 Unix 风格的文件系统中,一个点(.)表示当前目 ...

  2. 【pytorch学习】之微积分

    4 微积分 在2500年前,古希腊人把一个多边形分成三角形,并把它们的面积相加,才找到计算多边形面积的方法.为了求出曲线形状(比如圆)的面积,古希腊人在这样的形状上刻内接多边形.如图所示,内接多边形的 ...

  3. 讲座回顾丨基于 OpenYurt 和 EdgeX 的云边端协同新可能

    简介: 为帮助参赛选手更好地了解并运用相关技术,本次大赛将在 7 月至 9 月持续开展 3 轮技术培训,涵盖初.中.高不同层级,帮助开发者系统学习智能边缘系统知识.我们邀请到来自英特尔.VMware. ...

  4. 龙蜥社区成立系统运维SIG,重磅开源sysAK系统运维工具集

    简介:系统运维SIG致力于打造一个集主机管理.配置部署.监控报警.异常诊断.安全审计等一系列功能的自动化运维平台. ​ OpenAnolis 龙蜥社区(以下简称"龙蜥社区")正式成 ...

  5. iOS App 启动优化

    ​简介: 作为程序猿来说,"性能优化"是我们都很熟悉的词,也是我们需要不断努⼒以及持续进⾏的事情:其实优化是⼀个很⼤的课题,因为细分来说的话有⼤⼤⼩⼩⼗⼏种优化⽅向 ,但是切忌在实 ...

  6. [FAQ] Sortable 拖拽组件, 火狐浏览器中打开新窗口问题

      Q:用了 sortable 组件,在火狐浏览器中进行拖拽时,会打开新窗口 ? Sortable组件地址,https://github.com/SortableJS/Sortable 当前处理方式 ...

  7. dotnet C# 如果在构造函数抛出异常 是否可以拿到对象赋值的变量

    如果使用某个变量去获取某个类型的对象创建,但是在这个类型的构造函数调用时抛出异常,请问此变量是否可以拿到对应的对象 如下面代码 private void F1() { Foo foo = null; ...

  8. gin框架获取参数

    目录 httpext包 获取header头里的参数: scene := httpext.GetHeaderByName(ctx, "scene") // online / dev ...

  9. Linux中的which whereis locate

    which which会在PATH环境中搜寻可执行文件 whereis Linux会将系统里面所有的文件都搜集到一个数据库文件中,whereis从这个数据库文件里面寻找文件 locate locate ...

  10. JavaScript 数组常用方法整理

    数组变异方法 push() 数组末尾添加一个项目,返回新数组长度,arr.push(item)pop() 数组末尾删除一个元素,返回被删除元素,arr.pop()shift() 删除数组开头第1个元素 ...