字典树(Trie树相关)

208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods. (Medium)

Note:
You may assume that all inputs are consist of lowercase letters a-z.

分析:

字典树即前缀匹配树,在空间不是很影响的情况下一般采用如下数据结构存储Trie节点

 class TrieNode {
public:
// Initialize your data structure here.
bool isWord;
TrieNode* child[];
TrieNode(): isWord(false){
memset(child, NULL, sizeof(child));
}
};

所以插入、查找等操作比较直观,直接见程序。

代码:

 class TrieNode {
public:
// Initialize your data structure here.
bool isWord;
TrieNode* child[];
TrieNode(): isWord(false){
memset(child, NULL, sizeof(child));
}
}; class Trie {
public:
Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
void insert(string word) {
TrieNode* r = root;
for (int i = ; i < word.size(); ++i) {
if (r -> child[word[i] - 'a'] == NULL) {
r -> child[word[i] - 'a'] = new TrieNode(); }
r = r -> child[word[i] - 'a'];
}
r -> isWord = true;
} // Returns if the word is in the trie.
bool search(string word) {
TrieNode* r = root;
for (int i = ; i < word.size(); ++i) {
if (r -> child[word[i] - 'a'] == NULL) {
return false; }
r = r -> child[word[i] - 'a'];
}
if (r -> isWord) {
return true;
}
return false;
} // Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* r = root;
for (int i = ; i < prefix.size(); ++i) {
if (r -> child[prefix[i] - 'a'] == NULL) {
return false; }
r = r -> child[prefix[i] - 'a'];
}
return true;
} private:
TrieNode* root;
}; // Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

211. Add and Search Word - Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. (Medium)

For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

分析:

继续沿用字典树的思路,只不过加入了“.”通配符,所以在查找过程中加入DFS即可,用辅助函数helper

代码:

 class TrieNode {
public:
// Initialize your data structure here.
bool isWord;
TrieNode* child[];
TrieNode(): isWord(false){
memset(child, NULL, sizeof(child));
}
}; class Trie {
public:
Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
void insert(string word) {
TrieNode* r = root;
for (int i = ; i < word.size(); ++i) {
if (r -> child[word[i] - 'a'] == NULL) {
r -> child[word[i] - 'a'] = new TrieNode(); }
r = r -> child[word[i] - 'a'];
}
r -> isWord = true;
} //helper function for search, use to solve "." problem
bool helper(string word, int pos, TrieNode* curRoot) {
if (pos == word.size() && curRoot -> isWord) {
return true;
}
if (word[pos] != '.') {
if (curRoot -> child[word[pos] - 'a'] == NULL) {
return false;
}
else {
return helper(word, pos + , curRoot -> child[word[pos] - 'a']);
}
}
else {
bool flag = false;
for (int i = ; i < ; ++i) {
if (curRoot -> child[i] != NULL && helper(word, pos + , curRoot -> child[i]) ) {
flag = true;
}
}
return flag;
}
return true;
}
// Returns if the word is in the trie.
bool search(string word) {
return helper(word, , root);
} private:
TrieNode* root;
}; class WordDictionary {
public:
Trie dic;
// Adds a word into the data structure.
void addWord(string word) {
dic.insert(word);
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return dic.search(word);
}
}; // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
 

LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design的更多相关文章

  1. Leetcode211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

    设计一个支持以下两种操作的数据结构: void addWord(word) bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a- ...

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

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

  3. 【LeetCode】211. Add and Search Word - Data structure design

    Add and Search Word - Data structure design Design a data structure that supports the following two ...

  4. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  5. 【刷题-LeetCode】211. Add and Search Word - Data structure design

    Add and Search Word - Data structure design Design a data structure that supports the following two ...

  6. (*medium)LeetCode 211.Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  7. 211. Add and Search Word - Data structure design

    题目: Design a data structure that supports the following two operations: void addWord(word) bool sear ...

  8. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  9. Java for LeetCode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...

随机推荐

  1. git放弃本地所有未提交的修改

    1.未添加至暂存区的 git checkout . 2.已添加至暂存区的 git reset HEAD . git checkout .

  2. 用户测评 | EDAS Serverless 上手体验

    背景 最初, 是因为对 Serverless 这一概念感兴趣, 所以开始试用阿里云函数计算,使用过程中感受到了函数计算快速.按需付费和弹性伸缩等方面的优势,随后我在天气预报.发送短信等场景下开始了更深 ...

  3. Docx 生成word文档

    1.生成word代码 /// <summary> /// 生成word文档 /// </summary> /// <param name="tempPath&q ...

  4. TZ_06_SpringMVC_异常处理,自定义异常

    1.SpringMVC异常处理的方式 . 2. 异常处理思路 1>. Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServle ...

  5. [BZOJ3990][SDOI2015][LOJ#2181]-排序

    说实话,这个题真好(?) <BZOJ题面> <LOJ题面> 看到这个题,一时没有思路 但是 我想到了一个错解:归并 这个题真的有一点把我们的思路往归并上引 于是WA10 诶?我 ...

  6. netbeans 代码自动补全设置

    编辑器-----代码完成------语言选择"JAVA"------在如图红框中输入 @ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst ...

  7. python基础--闭包and装饰器

    闭包函数:函数内部定义的函数:引用了外部变量但非全局变量 装饰器:有了闭包的概念再去理解装饰器就会相对容易一些.python装饰器本质上就是一个函数,它可以让其他函数在不需要做任何代码变动的前提下增加 ...

  8. javascript之键盘事件的方法

    键盘事件包含onkeydown.onkeypress和onkeyup这三个事件 事件初始化 function keyDown(){} document.onkeydown = keyDown; //论 ...

  9. Yii 学习笔记

    Yii常用执行SQL方法 ====================================================== ================================ ...

  10. jstree设置checkbox单选

    jstree设置插件checkbox只允许单选 jstree version console.log($.jstree.version); 3.3.8 单选配置参数: $.jstree.default ...