208. 实现 Trie (前缀树)
2024-09-06 20:36:40
主要是记录一下这个数据结构。
比如这个trie树,包含三个单词:sea,sells,she。
代码:
class Trie {
bool isWord;
vector<Trie*> children;
public:
/** Initialize your data structure here. */
Trie() {
isWord=false;
children.assign(,nullptr);
} /** Inserts a word into the trie. */
void insert(string word) {
if(word.empty()){return;}
auto cur=this;
for(int i=;i<word.size();++i){
if(cur->children[word[i]-'a']==nullptr){
cur->children[word[i]-'a']=new Trie();
}
cur=cur->children[word[i]-'a'];
}
cur->isWord=true;
} /** Returns if the word is in the trie. */
bool search(string word) {
auto cur=this;
for(int i=;i<word.size();++i){
if(cur->children[word[i]-'a']==nullptr){
return false;
}
cur=cur->children[word[i]-'a'];
}
return cur->isWord;
} /** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
auto cur=this;
for(int i=;i<prefix.size();++i){
if(cur->children[prefix[i]-'a']==nullptr){
return false;
}
cur=cur->children[prefix[i]-'a'];
}
return true;
}
}; /**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
最新文章
- Codeforces Round #352 (Div. 2)
- [转]架构蓝图--软件架构 ";4+1"; 视图模型
- 背水一战 Windows 10 (5) - UI: 标题栏
- Java-基础练习1
- 7月15日学习之BOM
- objective-c宏定义
- Linux 下实时查看日志
- C#读写Shapefile
- 邓_ ThinkPhp框架
- 学习总结javascript和ajax,php,和css
- 秒懂C#通过Emit动态生成代码
- Python 判断文件/目录是否存在
- jenkins使用jacoco插件检测代码覆盖率(八)
- metasploit framework(十一):获取漏洞信息
- Kafka学习之路 (三)Kafka的高可用
- 安装了XAMPP,PHP怎么显示中文
- zendframework配置篇
- Quercus-基于 Java 的 PHP 框架
- Web服务器对比介绍
- 微信小程序挑一挑辅助