第73天(中等题 数据结构)
打卡第七十三天
2道中等题

题目:

Trie Tree 的实现:





性质:

代码:
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
Trie() {
isEnd = false;
memset(next, 0, sizeof(next));// 将所有子节点指针初始化为NULL
}
void insert(string word) {//向 Trie 中插入一个单词 word
Trie* node = this;
for (char c : word) {
if (node->next[c-'a'] == NULL) {
node->next[c-'a'] = new Trie();
}
node = node->next[c-'a'];
}
node->isEnd = true;
}
bool search(string word) {//查找 Trie 中是否存在单词 word
Trie* node = this;
for (char c : word) {
node = node->next[c - 'a'];
if (node == NULL) {
return false;
}
}
return node->isEnd;
}
bool startsWith(string prefix) {//判断 Trie 中是或有以 prefix 为前缀的单词
Trie* node = this;
for (char c : prefix) {
node = node->next[c-'a'];
if (node == NULL) {
return false;
}
}
return true;
}
};
耗时≈一小时 明天继续

浙公网安备 33010602011771号