当前位置: 代码迷 >> 综合 >> Leetcode 208. 实现 Trie (前缀树)(DAY 86) ---- Leetcode Hot 100
  详细解决方案

Leetcode 208. 实现 Trie (前缀树)(DAY 86) ---- Leetcode Hot 100

热度:50   发布时间:2023-11-17 18:49:54.0

文章目录

    • 原题题目
    • 代码实现(首学前缀树)
    • 代码实现(二刷自解 DAY 144 C++)


原题题目


在这里插入图片描述


代码实现(首学前缀树)


class Trie {
    
public:/** Initialize your data structure here. */vector<Trie*> children;bool isEnd;//三刷后 系统学习完c++补充//这种不在初始化列表初始化的习惯 相当糟糕Trie() {
    children = vector<Trie*>(26,nullptr); isEnd = false;}/** Inserts a word into the trie. */void insert(string word) {
    Trie* temp = this;for(const char& chr:word){
    if(temp->children[chr-'a'] == nullptr)temp->children[chr-'a'] = new Trie();temp = temp->children[chr-'a'];}temp->isEnd = true;}/** Returns if the word is in the trie. */bool search(string word) {
    auto temp = this;for(const auto& chr:word){
    if(temp->children[chr-'a'] == nullptr)  return false;temp = temp->children[chr-'a'];}if(temp->isEnd) return true;else    return false;}/** Returns if there is any word in the trie that starts with the given prefix. */bool startsWith(string prefix) {
    auto temp = this;for(const auto& chr:prefix){
    if(temp->children[chr-'a'] == nullptr)  return false;temp = temp->children[chr-'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);*/

代码实现(二刷自解 DAY 144 C++)


class Trie {
    
public:vector<Trie*> trie_tree;bool isend;Trie():trie_tree(26,nullptr),isend(false) {
    }void insert(string word) {
    int size = word.size();auto ptr = this;for(int i = 0;i < size;++i){
    auto chr = word[i];if(!ptr->trie_tree[chr - 'a'])ptr->trie_tree[chr - 'a'] = new Trie();ptr = ptr->trie_tree[chr - 'a'];}ptr->isend = true;}bool search(string word) const {
    auto ptr = this;for(const auto& chr:word){
    if(!ptr->trie_tree[chr - 'a'])return false;ptr = ptr->trie_tree[chr - 'a'];}return ptr->isend;}bool startsWith(string prefix) const {
    auto ptr = this;for(const auto& chr:prefix){
    if(!ptr->trie_tree[chr - 'a'])return false;ptr = ptr->trie_tree[chr - '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);*/