leetcode 211. Add and Search Word

题目链接

写一个数据结构, 支持两种操作。 加入一个字符串, 查找一个字符串是否存在。查找的时候, '.'可以代表任意一个字符。

显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可以。 具体dfs方法看代码。

struct node
{
    node *next[26];
    int idEnd;
    node() {
        memset(next, NULL, sizeof(next));
        idEnd = 0;
    }
};
class WordDictionary {
public:
    // Adds a word into the data structure.
    node *root = new node();
    void addWord(string word) {
        node *p = root;
        int len = word.size();
        for(int i = 0; i<len; i++) {
            if(p->next[word[i]-'a'] == NULL)
                p->next[word[i]-'a'] = new node();
            p = p->next[word[i]-'a'];
        }
        p->idEnd = 1;
        return ;
    }
    int dfs(string word, int pos, node *p) {            //pos是代表当前是在哪一位。
        if(pos == word.size())
            return p->idEnd;
        int len = word.size();
        for(int i = pos; i<len; i++) {
            if(word[i] == '.') {
                for(int j = 0; j<26; j++) {
                    if(p->next[j] == NULL)
                        continue;
                    if(dfs(word, pos+1, p->next[j]))
                        return 1;
                }
                return 0;
            } else if(p->next[word[i]-'a'] != NULL) {
                return dfs(word, pos+1, p->next[word[i]-'a']);
            } else {
                return 0;
            }
        }
    }
    // 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 dfs(word, 0, root);
    }
};
原文地址:https://www.cnblogs.com/yohaha/p/5119997.html