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;
};

最新文章

  1. docker进入后台运行的容器
  2. Javascript函数式编程要掌握的知识点讲解
  3. 鼠标hover某个元素时其属性表现Css transition 过渡效果(以宽高属性居中放大为例)
  4. Eclipse IDE for Java EE Developers 与 Eclipse Classic(Eclipse Standard)区别
  5. 手势估计- Hand Pose Estimation
  6. KnockoutJS 3.X API 第四章 数据绑定(4) 控制流with绑定
  7. 应用Spring MVC发布restful服务是怎样的一种体验
  8. 项目源码--JSP在线客服系统(SSH框架技术)源码
  9. 基于visual Studio2013解决C语言竞赛题之0702函数设计
  10. Less的Mixin
  11. ElasticSearch 学习记录之集群分片内部原理
  12. Angular开发实践(三):剖析Angular Component
  13. ubuntu下安装 python 常用软件
  14. 【.NET Core项目实战-统一认证平台】第十三章 授权篇-如何强制有效令牌过期
  15. Angular6封装http请求
  16. arduino 522样本中文注释
  17. nat表使用
  18. 费马定理&欧拉定理
  19. (转)go语言nsq源码解读二 nsqlookupd、nsqd与nsqadmin
  20. C#下实现的基础K-MEANS多维聚类

热门文章

  1. Linux下提取IP至文件
  2. UML 序列图一点理解
  3. percona-xtrabackup备份mysql
  4. commons-fileupload实现文件上传下载
  5. w
  6. C#的面向对象特性之封装
  7. 网易前端JavaScript编码规范
  8. [转]ASP.NET Web.Config 读写辅助类
  9. Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式
  10. Sqlite实现默认时间为当前时间列的方法(转)