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;
}

原文地址:https://www.cnblogs.com/crackpotisback/p/10208107.html

时间: 2024-08-01 11:30:54

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

[LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计

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

[LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

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

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

题目描述: 方法一: class WordDictionary: def __init__(self): """ Initialize your data structure here. """ #from collections import defaultdict self.lookup = {} def addWord(self, word: str) -> None: """ Adds a word i

[1205 单词翻转] 解题报告

题目描述 Description 给出一个英语句子,希望你把句子里的单词顺序都翻转过来 输入描述 Input Description 输入包括一个英语句子. 输出描述 Output Description 按单词的顺序把单词倒序输出 样例输入 Sample Input I love you 样例输出 Sample Output you love I 数据范围及提示 Data Size & Hint 简单的字符串操作 解题思路: 步骤一:简单来讲可以使用两次翻转实现,第一次对整体做一个翻转,得到&q

【LeetCode】Find Minimum in Rotated Sorted Array 解题报告

今天看到LeetCode OJ题目下方多了"Show Tags"功能.我觉着挺好,方便刚開始学习的人分类练习.同一时候也是解题时的思路提示. [题目] Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no

LeetCode Roman to Integer 罗马字符转数字 解题报告

https://oj.leetcode.com/problems/roman-to-integer/ Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 把一个给定的罗马字符转为数字.首先要了解罗马字符表示的规则. 一,羅馬數字共有7個,即I(1).V(5).X(10).L(50).C(100).D(500)和M(1000). 二,在

LeetCode OJ 238. Product of Array Except Self 解题报告

题目链接:https://leetcode.com/problems/product-of-array-except-self/ 238. Product of Array Except Self My Submissions Question Total Accepted: 36393 Total Submissions: 87262 Difficulty: Medium Given an array of n integers where n > 1, nums, return an arr

LeetCode: Remove Nth Node From End of List 解题报告

Remove Nth Node From End of List Total Accepted: 46720 Total Submissions: 168596My Submissions Question Solution Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5,

【LeetCode】Substring with Concatenation of All Words 解题报告

[题目] You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given: