leetcode Add and Search Word - Data structure design

本文详细阐述了如何优化字典数据结构,从使用vector存储改进为采用Trie树实现,以提高大数据查询效率。通过实例演示了正则表达式的应用,并对比了两种方法的时间复杂度。

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

很久没刷题,再次面对trie居然没有第一时间想起来

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.

For 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.

意思很简单,就是支持一个正则的.

第一份代码 用vector存储在一次比较果断timeout

#include <vector>
#include <string>
#include <algorithm>
using std::vector;
using std::string;

class WordDictionary {
    vector<string> vec;
public:

    // Adds a word into the data structure.
    void addWord(string word) {
        vec.push_back(word);
    }

    // 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) {
        vector<string>::iterator iter;
        iter = find_if(vec.begin(),vec.end(),[=](string str)
        {
            return [=](string l,string r)
            {
                size_t pos = l.size();
                if (pos != r.size()) return false;
                
                for (int i =0;i != pos;++i){
                    if (l[i] != r[i] && l[i] != '.') return false;
                }
                return true;
            }(word,str);
        });
        
        if (iter != vec.end()){
            return true;
        }
        return false;
    }
};


后来想到这种大数据查询一般用trie树马上改

#include <vector>
#include <string>
#include <algorithm>
using std::vector;
using std::string;

class WordDictionary {
    struct trie
    {
        struct trie * next[26];
        bool end;
    };
    
    struct trie * root;
    void creat(struct trie *&root)
    {
        root = new struct trie;
        root->end = false;
         memset(root->next,0,sizeof root->next);
    }
    bool search(string word,struct trie * root)
    {
        // word is not end 
        if (root == NULL) return false;
        size_t len = word.size();
        for (int i =0;i!=len;++i){
            size_t pos = word[i] - 'a';
            if (word[i] != '.'){
                if (root->next[pos] == NULL) return false;
                root = root->next[pos];
            }else{
                // word[i] is . ,so we should handle it
               for (int k =0;k!=26;++k){
                   if (search(word.substr(i+1),root->next[k])) return true;
               }
			   return false;
            }
        }
        
        
        return root->end;
    }
public:
    WordDictionary()
    {
        creat(root);
    }
    ~WordDictionary(){delete root;}
    // Adds a word into the data structure.
    void addWord(string word) {
        struct trie * temp = this->root;
		//struct trie * next = temp;
        for_each(word.begin(),word.end(),[&](char c)
        {
            size_t pos = c- 'a';
            if (temp->next[pos] == NULL){
                creat(temp->next[pos]);
            }
			temp = temp->next[pos];
        });
        temp->end = 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 search(word,root);
    }
};

int main()
{
	WordDictionary wordDictionary;
	wordDictionary.addWord("ab");
	wordDictionary.search("a.");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值