Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 211. 添加与搜索单词 - 数据结构设计 #57

Open
Animenzzzz opened this issue Aug 21, 2019 · 0 comments
Open

[LeetCode] 211. 添加与搜索单词 - 数据结构设计 #57

Animenzzzz opened this issue Aug 21, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

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 组成的。

解题思路:这题是常规的字典树,唯一不同的是需要匹配正则表达式。其他的初始化操作都一样,在搜索时需要修改。参考的 grandyang/leetcode#211
当遇到 . 时,需要匹配下一个字符,跳过 . 。自己做的时候,第一个条件写成了 if(p && p->isWordEnd && index == word.size()) return true; 总报树的child越界。。。蛋疼。。。

C++解题:

class TrieNode{
public:
    TrieNode *child[26];
    bool isWordEnd;
    TrieNode():isWordEnd(false){
        for (int i = 0; i < 26; i++) child[i] = nullptr;
    }
};
class WordDictionary {
public:

    WordDictionary() {
        
    }
    
    void addWord(string word) {
        TrieNode *p = root;
        for(char cc:word){
            int index = cc - 'a';
            if(!p->child[index]) p->child[index] = new TrieNode();
            p = p->child[index];
        }
        p->isWordEnd = true;
    }
    
    bool search(string word) {
        return searchWord(word,0,root);
    }

    bool searchWord(string &word,int index,TrieNode *p){
        if(index == word.size()) return p->isWordEnd;
        if(word[index] == '.'){
            for (auto &a : p->child) {
                if (a && searchWord(word, index + 1,a)) return true;
            }
            return false;
        }else{
            return p->child[word[index] - 'a'] && searchWord(word, index + 1,p->child[word[index] - 'a']);
        }
    }
private:
    TrieNode *root = new TrieNode();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant