前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0211 - Add and Search Word - Data structure design

LeetCode 0211 - Add and Search Word - Data structure design

作者头像
Reck Zhang
发布2021-08-11 12:08:42
2230
发布2021-08-11 12:08:42
举报
文章被收录于专栏:Reck ZhangReck Zhang

Add and Search Word - Data structure design

Desicription

Design a data structure that supports the following two operations:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.

Solution

代码语言:javascript
复制
/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * bool param_2 = obj.search(word);
 */
class WordDictionary {
private:
    class TrieNode {
    public:
        bool isWord = false;
        TrieNode* children[26] = {nullptr};
    };
    TrieNode* root = new TrieNode();
public:
    /** Initialize your data structure here. */
    WordDictionary() = default;

    /** Adds a word into the data structure. */
    void addWord(string word) {
        TrieNode* run = root;
        for(char c : word) {
            if(nullptr == run->children[c - 'a'])
                run->children[c - 'a'] = new TrieNode();
            run = run->children[c - 'a'];
        }
        run->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 query(std::move(word), root);
    }
    bool query(string word, TrieNode* run, int index = 0) {
        for(int i = index; word[i]; i++) {
            if(nullptr != run && word[i] != '.')
                run = run->children[word[i] - 'a'];
            else if(nullptr != run && word[i] == '.') {
                TrieNode* tmp = run;
                for(char c = 'a'; c <= 'z'; c++) {
                    word[i] = c;
                    run = tmp->children[word[i] - 'a'];
                    if(query(word, run, i+1))
                        return true;
                }
            }
            else break;
        }
        return run && run->isWord;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Add and Search Word - Data structure design
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档