leetcode 211. 添加与搜索单词 - 数据结构设计 解题报告

设计一个支持以下两种操作的数据结构:

void addWord(word)
bool search(word)

search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 .a-z. 可以表示任何一个字母。

示例:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

说明:

你可以假设所有单词都是由小写字母 a-z 组成的。

解题思路

直接用字典树(trie)即可,至于.匹配符直接利用回溯即可。

#include<bits/stdc++.h>

using namespace std;


const int nch = 26;
const int maxn = 200010;

static auto x = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    return 0;
}
();

struct Node {
    int ch[nch];
    bool flag;

    void reset() {
        for(int i = 0; i < nch; ++i) {
            ch[i] = -1;
        }
        flag = false;
    }
};

Node tree[maxn];

class WordDictionary {
public:
    /** Initialize your data structure here. */
    int tot;
    WordDictionary() {
        tree[tot = 0].reset();
    }

    /** Adds a word into the data structure. */
    void addWord(string word) {
        int root = 0;
        for(auto &chr:word) {
            if(tree[root].ch[chr - 'a'] == -1) {
                tree[root].ch[chr - 'a'] = ++tot;
                tree[tot].reset();
            }
            root = tree[root].ch[chr - 'a'];
        }
        tree[root].flag = 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, 0, 0);
    }

    bool _search(string &word, int cur, int root) {
        if(cur == word.size() && tree[root].flag)
            return true;
        if(cur >= word.size() or root == -1)
            return false;
        if(word[cur] == '.') {
            for(int i = 0; i < nch; ++i) {
                if(tree[root].ch[i] != -1 && _search(word, cur + 1, tree[root].ch[i]))
                    return true;
            }
            return false;
        }
        if(tree[root].ch[word[cur]-'a'] != -1)
            return _search(word, cur + 1, tree[root].ch[word[cur]-'a']);
        return false;
    }
};

int main() {

    return 0;
}

posted @   狂徒归来  阅读(418)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示