设计一个支持以下两种操作的数据结构:

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

最新文章

  1. js MATH
  2. 锋利的jQuery-1-- :的用法
  3. expect实现交互式脚本
  4. Rs2008内存管理策略
  5. 2016 ACM/ICPC Asia Regional Qingdao Online HDU5879
  6. c#图像处理入门(-bitmap类和图像像素值获取方法) 转
  7. (笔记)angular选项卡变色
  8. 13、主线程任务太多导致异常退出(The application may be doing too much work on its main thread)
  9. iOS 下拉菜单 FFDropDownMenu自定义下拉菜单样式实战-b
  10. 36、Android Bitmap 全面解析
  11. 不用找了,比较全的signalR例子已经为你准备好了.
  12. Unicode解码、URL编码/解码
  13. Scanner类及正则表达式
  14. 浩哥解析MyBatis源码(八)——Type类型模块之TypeAliasRegistry(类型别名注册器)
  15. cocos2dx 中触摸事件分发一些解读
  16. Machine Learning &amp;&amp;Deep Learning&amp;&amp;Sklearn
  17. UML类图新手入门级介绍(转)
  18. Elasticsearch索引模板和别名
  19. 06、action操作开发实战
  20. QT使用MSVC编译器输出中文乱码问题解决方法

热门文章

  1. IceCTF-Matrix
  2. ArrayList底层代码解析笔记
  3. 8u ftp 可以连接但是无法获取目录的解决办法:无法打开传输通道。原因:由于...
  4. Android SDK中无法安装HAXM installer
  5. this.$router.push
  6. JAVA java
  7. SPOJ:[DIVCNT3]Counting Divisors
  8. delphi windows操作
  9. 笨办法学Python记录--习题18 变量 函数 help的由来;if语句,循环和列表,冒泡排序,判断输入字符串的方法
  10. docker 环境搭建步骤