[LintCode] Implement Trie 实现字典树
2024-10-18 12:26:01
Implement a trie with insert, search, and startsWith methods.
Have you met this question in a real interview?
Example
Note
You may assume that all inputs are consist of lowercase letters a-z.
LeetCode上的原题,请参见我之前的博客Implement Trie (Prefix Tree) 实现字典树(前缀树)。
/**
* Your Trie object will be instantiated and called as such:
* Trie trie;
* trie.insert("lintcode");
* trie.search("lint"); will return false
* trie.startsWith("lint"); will return true
*/
class TrieNode {
public:
// Initialize your data structure here.
TrieNode *child[];
bool isWord;
TrieNode(): isWord(false) {
for (auto & a : child) a = NULL;
}
}; class Trie {
public:
Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
void insert(string word) {
TrieNode *p = root;
for (auto &a : word) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
} // Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = root;
for (auto &a : word) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
return p->isWord;
} // Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p = root;
for (auto &a : prefix) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
return true;
} private:
TrieNode* root;
};
最新文章
- docker进入后台运行的容器
- Javascript函数式编程要掌握的知识点讲解
- 鼠标hover某个元素时其属性表现Css transition 过渡效果(以宽高属性居中放大为例)
- Eclipse IDE for Java EE Developers 与 Eclipse Classic(Eclipse Standard)区别
- 手势估计- Hand Pose Estimation
- KnockoutJS 3.X API 第四章 数据绑定(4) 控制流with绑定
- 应用Spring MVC发布restful服务是怎样的一种体验
- 项目源码--JSP在线客服系统(SSH框架技术)源码
- 基于visual Studio2013解决C语言竞赛题之0702函数设计
- Less的Mixin
- ElasticSearch 学习记录之集群分片内部原理
- Angular开发实践(三):剖析Angular Component
- ubuntu下安装 python 常用软件
- 【.NET Core项目实战-统一认证平台】第十三章 授权篇-如何强制有效令牌过期
- Angular6封装http请求
- arduino 522样本中文注释
- nat表使用
- 费马定理&;欧拉定理
- (转)go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
- C#下实现的基础K-MEANS多维聚类