LeetCode #211 - Add and Search Word - Data structure design

本文介绍了一种使用前缀树(Trie)的数据结构来实现一个支持单词添加和搜索功能的字典。该字典能够搜索具体的单词或包含通配符'.'的正则表达式字符串,其中'.'可以代表任意一个字母。通过示例展示了如何添加单词以及如何进行精确和模糊搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Design a data structure that supports the following two operations:

void addWord(word)

bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")

addWord("dad")

addWord("mad")

search("pad") -> false

search("bad") -> true

search(".ad") -> true

search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

由于可以进行插入操作,采用前缀树可以实现。

class WordDictionary {
public:
    struct TrieNode{
    public:    
        char c;
        TrieNode* v[26];
        bool isWord = false;
        TrieNode(): c('#') {
            for(int i = 0; i < 26; i++) v[i] = NULL;
        } 
    };
    
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        TrieNode* p = root;
        for(int i = 0; i < word.size(); i++)
        {
            int j = word[i] - 'a';
            if (p->v[j] == NULL) p->v[j] = new TrieNode();
            p = p->v[j];
        }
        p->isWord = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word) {
        return helper(word, root, 0);
    }
    
    bool helper(string word, TrieNode* p, int i)
    {
        if(i == word.size()) return p->isWord;
        if(word[i] != '.')
        {
            int j = word[i] - 'a';
            if(p->v[j] == NULL) return false;
            else return helper(word, p->v[j], i + 1);
        }
        else
        {
            bool isWord = false;
            for(int j = 0; j < 26; j++)
                if(p->v[j] != NULL && helper(word, p->v[j], i + 1)) isWord = true;;
            return isWord;
        }
    }

private:
    TrieNode* root;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值