leetcode Hot 100系列
提示:小白个人理解,如有错误敬请谅解!
一、核心操作
- 建立Node节点,每个节点都包含一个是否为结尾的标识符以及26位的Node数组
- 对于Trie,直接将根节点root作为类的成员变量,这样每次遍历直接从root往下遍历即可
- 对于插入,直接设置cur指向根节点,然后逐层向下搜索,如果没有搜索到则创建这个节点,然后再将cur向下移动,最后在cur停止的这个节点将标识符设置为true
- 对于查找和查找前缀,都可以用同一个find函数,也是将cur从root开始逐层往下找,如果有一个节点不存在,则返回0,如果全都找到了但是最后一个节点的标识符不为true,则返回1,否则返回2,对于查找来说,只有返回的是2是才返回true,但对于查找前缀来说,只要返回的不是0就可以
二、外层配合操作
- 无
三、核心模式代码
代码如下:
struct Node
{
bool isEnd;
Node* son[26] {};
// Node(bool x) : isEnd(x) {}
};
class Trie {
public:
Node* root=new Node();
int find(std::string word)
{
Node* cur=root;
for(auto s : word)
{
if(!cur->son[s-'a'])
return 0;
else
cur=cur->son[s-'a'];
}
if(cur->isEnd)
return 2;
else
return 1;
}
void insert(std::string word) {
Node* cur=root;
for(auto s : word)
{
if(!cur->son[s-'a'])
cur->son[s-'a']=new Node();
cur=cur->son[s-'a'];
}
cur->isEnd=true;
}
bool search(std::string word) {
int res=find(word);
if(res!=2)
return false;
return true;
}
bool startsWith(std::string prefix) {
int res=find(prefix);
if(!res)
return false;
return true;
}
};
总结
- 类外定义节点,类内定义根节点