Leetcode211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计
2024-08-20 15:02:38
设计一个支持以下两种操作的数据结构:
void addWord(word) bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
典型的字典树,前缀树的用法
class WordDictionary {
public:
struct TrieNode
{
TrieNode(): isword(false), children(26, nullptr){}
~TrieNode()
{
for(TrieNode* child : children)
{
if(child)
delete child;
}
}
bool isword;
vector<TrieNode*> children;
};
TrieNode* root;
/** Initialize your data structure here. */
WordDictionary() : root(new TrieNode()){
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode *p = root;
for(char c : word)
{
if(p ->children[c - 'a'] == nullptr)
{
p ->children[c - 'a'] = new TrieNode();
}
p = p ->children[c - 'a'];
}
p ->isword = true;
}
/** 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) const{
TrieNode *p = root;
for(int i = 0; i < word.size(); i++)
{
if(word[i] == '.')
{
for(int j = 0; j < 26; j++)
{
if(p ->children[j])
{
if(Find(string(word.begin() + i + 1, word.end()), p ->children[j]))
return true;
}
}
return false;
}
else
{
p = p ->children[word[i] - 'a'];
if(p == nullptr)
return false;
}
}
if(p ->isword)
return true;
return false;
}
const bool Find(string word, TrieNode* p) const
{
for(int i = 0; i < word.size(); i++)
{
if(word[i] == '.')
{
for(int j = 0; j < 26; j++)
{
if(p ->children[j])
{
if(Find(string(word.begin() + i + 1, word.end()), p ->children[j]))
return true;
}
}
return false;
}
else
{
p = p ->children[word[i] - 'a'];
if(p == nullptr)
return false;
}
}
if(p ->isword)
return true;
return false;
}
};
最新文章
- js MATH
- 锋利的jQuery-1-- :的用法
- expect实现交互式脚本
- Rs2008内存管理策略
- 2016 ACM/ICPC Asia Regional Qingdao Online HDU5879
- c#图像处理入门(-bitmap类和图像像素值获取方法) 转
- (笔记)angular选项卡变色
- 13、主线程任务太多导致异常退出(The application may be doing too much work on its main thread)
- iOS 下拉菜单 FFDropDownMenu自定义下拉菜单样式实战-b
- 36、Android Bitmap 全面解析
- 不用找了,比较全的signalR例子已经为你准备好了.
- Unicode解码、URL编码/解码
- Scanner类及正则表达式
- 浩哥解析MyBatis源码(八)——Type类型模块之TypeAliasRegistry(类型别名注册器)
- cocos2dx 中触摸事件分发一些解读
- Machine Learning &;&;Deep Learning&;&;Sklearn
- UML类图新手入门级介绍(转)
- Elasticsearch索引模板和别名
- 06、action操作开发实战
- QT使用MSVC编译器输出中文乱码问题解决方法
热门文章
- IceCTF-Matrix
- ArrayList底层代码解析笔记
- 8u ftp 可以连接但是无法获取目录的解决办法:无法打开传输通道。原因:由于...
- Android SDK中无法安装HAXM installer
- this.$router.push
- JAVA java
- SPOJ:[DIVCNT3]Counting Divisors
- delphi windows操作
- 笨办法学Python记录--习题18 变量 函数 help的由来;if语句,循环和列表,冒泡排序,判断输入字符串的方法
- docker 环境搭建步骤