211. 添加与搜索单词 - 数据结构设计

211. 添加与搜索单词 - 数据结构设计


题目链接:211. 添加与搜索单词 - 数据结构设计

代码如下:

//前缀树 参考leetcode官方题解
class TrieNode {
   
public:
    vector<TrieNode*> children;
    bool isEnd;
    TrieNode() : children(26), isEnd(false) {
   }
};

class WordDictionary {
   
private:
    TrieNode* trie;
    void insert(TrieNode* root, const string& word) {
   
        TrieNode* node = root;
        for (int i = 0; i < word.size(); i++) {
   
            if (node->children[word[i] - 'a'] == nullptr)
                node->children[word[i] - 'a'] = new TrieNode();
            node = node->children[word[i] - 'a'];
        }
        node->isEnd = true;
    }

    //深度遍历
    bool dfs(const string& word, int index, TrieNode* node) {
   
        if (index ==
            word.size()) //如果到了单词的末尾。看看前缀树是否到达单词末尾
            return node->isEnd;
        if (word[index] >= 'a' && word[index] <= 'z') {
    //如果是字母,就继续查找
            TrieNode* child = node->children[word[index] - 'a'];
            if (child != nullptr && dfs(word, index + 1, child))
                return true;
        } else if (word[index] ==
                   '.') {
    //如果是.,就把26个字母都查找一遍进行匹配
            for (int i = 0; i < 26; i++) {
   
                TrieNode* child = node->children[i];
                if (child && dfs(word, index + 1, child))
                    return true;
            }
        }
        return false;
    }

public:
    WordDictionary() {
    trie = new TrieNode(); }

    void addWord(string word) {
    insert(trie, word); }

    bool search(string word) {
    return dfs(word, 0, trie); }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */

相关推荐

  1. LeetCode 211.添加搜索单词 - 数据结构设计 题解

    2024-01-30 19:48:01       42 阅读
  2. 211. 添加搜索单词 - 数据结构设计

    2024-01-30 19:48:01       46 阅读
  3. 添加搜索单词 - 数据结构设计[中等]

    2024-01-30 19:48:01       37 阅读
  4. Leetcode. 212 单词搜索II

    2024-01-30 19:48:01       35 阅读
  5. LeetCode 212.单词搜索II

    2024-01-30 19:48:01       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-30 19:48:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-30 19:48:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-30 19:48:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-30 19:48:01       20 阅读

热门阅读

  1. TCP的三次握手和四次挥手

    2024-01-30 19:48:01       40 阅读
  2. 前端面试题-说说你了解的js数据结构?(2024.1.29)

    2024-01-30 19:48:01       38 阅读
  3. 【C++】operator()

    2024-01-30 19:48:01       44 阅读
  4. 【城市大脑】城市数字大脑:智慧城市的新引擎

    2024-01-30 19:48:01       35 阅读
  5. 5.llama.cpp编译及使用

    2024-01-30 19:48:01       37 阅读
  6. 力扣0108——将有序数组转换为二叉搜索树

    2024-01-30 19:48:01       44 阅读
  7. 01_02_mysql02_DDL

    2024-01-30 19:48:01       43 阅读
  8. 力扣0110——平衡二叉树

    2024-01-30 19:48:01       46 阅读