leetcode 211. Add and Search Word

来源:互联网 发布:推荐系统 知乎 编辑:程序博客网 时间:2024/05/19 01:31

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.

For example:

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

Note:
You may assume that all words are consist of lowercase letters a-z.

标准字典树。


class TNode{public:        char key;    bool isword;    TNode *child[26];    TNode()    {        key=0;        isword=false;        memset(child, 0, sizeof(TNode *) * 26);    }        TNode(char c)    {        key=c;        isword=false;        memset(child, 0, sizeof(TNode *) * 26);    }};class WordDictionary {private:    TNode *root;    public:    /** Initialize your data structure here. */    WordDictionary()     {        root = new TNode();        }        /** Adds a word into the data structure. */    void addWord(string word)     {        TNode *p = root;        for (int i = 0; i < word.size(); i++)        {            if ( p->child[word[i]-'a'] == 0 )            {                TNode *pNode = new TNode(word[i]);                 p->child[word[i]-'a'] = pNode;            }            p = p->child[word[i]-'a'];        }         p->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 search(root, word, 0);    }        bool search(TNode * pNode, string word, int pos)    {        TNode *p = pNode;        for(int i = pos; i < word.size(); i++)        {            if (p && word[i] == '.')                {                for(int j = 0; j < 26; j++)                {                    if (search(p->child[j], word, i+1))                        return true;                }                return false;            }            else if (p && word[i] != '.')            {                p = p->child[word[i]-'a'];                }            else                break;        }        return (p && p->isword);    }};/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * bool param_2 = obj.search(word); */


原创粉丝点击