LeetCode 211. Add and Search Word - Data structure design
2015-08-10 10:50
591 查看
借用LeetCode 208. Implement Trie (Prefix Tree)中设计的字典树,特判查询字符为.时的情况即可。
注意:
成员变量的初始化应放在构造函数的initializing list而不是body中,使成员变量只被初始化一次,没有被再次赋值;
使用shared_ptr代替裸指针来管理内存。
代码:
class TrieNode
{
public:
TrieNode(): is_word(false) {}
void insert(const string& word)
{
if (!word.empty())
{
nodes[word.front()] =
nodes[word.front()] != nullptr ?
nodes[word.front()] : shared_ptr<TrieNode>(new TrieNode);
nodes[word.front()]->insert(word.substr(1));
} else
{
is_word = true;
}
}
bool search(string word)
{
if (!word.empty())
{
if (word.front() == '.')
{
bool ret = false;
for (auto it = nodes.begin(); it != nodes.end() && !ret; ++ it)
{
ret = ret || it->second->search(word.substr(1));
}
return ret;
} else if (nodes.find(word.front()) != nodes.end())
{
return nodes[word.front()]->search(word.substr(1));
} else
{
return false;
}
}
return is_word;
}
map<char, shared_ptr<TrieNode>> nodes;
bool is_word;
};
class WordDictionary
{
public:
WordDictionary(): root(shared_ptr<TrieNode>(new TrieNode())) {}
void addWord(string word)
{
root->insert(word);
}
bool search(string word)
{
return root->search(word);
}
private:
shared_ptr<TrieNode> root;
};
注意:
成员变量的初始化应放在构造函数的initializing list而不是body中,使成员变量只被初始化一次,没有被再次赋值;
使用shared_ptr代替裸指针来管理内存。
代码:
class TrieNode
{
public:
TrieNode(): is_word(false) {}
void insert(const string& word)
{
if (!word.empty())
{
nodes[word.front()] =
nodes[word.front()] != nullptr ?
nodes[word.front()] : shared_ptr<TrieNode>(new TrieNode);
nodes[word.front()]->insert(word.substr(1));
} else
{
is_word = true;
}
}
bool search(string word)
{
if (!word.empty())
{
if (word.front() == '.')
{
bool ret = false;
for (auto it = nodes.begin(); it != nodes.end() && !ret; ++ it)
{
ret = ret || it->second->search(word.substr(1));
}
return ret;
} else if (nodes.find(word.front()) != nodes.end())
{
return nodes[word.front()]->search(word.substr(1));
} else
{
return false;
}
}
return is_word;
}
map<char, shared_ptr<TrieNode>> nodes;
bool is_word;
};
class WordDictionary
{
public:
WordDictionary(): root(shared_ptr<TrieNode>(new TrieNode())) {}
void addWord(string word)
{
root->insert(word);
}
bool search(string word)
{
return root->search(word);
}
private:
shared_ptr<TrieNode> root;
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解