Leetcode173: Add and Search Word - Data structure design

来源:互联网 发布:淘宝店铺怎么写标题 编辑:程序博客网 时间:2024/06/05 06:43

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.

利用171的前缀树来实现。

class TrieNode {  public:      // Initialize your data structure here.      char var;        bool istrue;    TrieNode* children[26];        // Initialize your data structure here.        TrieNode() {            var = 0;            memset(children, 0x0, sizeof(TreeNode*)*26);            istrue = false;    }        TrieNode(char c){            var = c;            memset(children, 0x0, sizeof(TreeNode*)*26);        istrue = false;    }    };  class WordDictionary {private:    TrieNode *root;public:    WordDictionary()    {        root = new TrieNode();    }    // Adds a word into the data structure.    void addWord(string word) {        TrieNode* node = root;        for(int i = 0; i < word.length(); i++)        {            char c= word[i];                if (node->children[c-'a'] == 0)                {                    TrieNode *pNew = new TrieNode(c);                    node->children[c-'a'] = pNew;                }                node = node->children[c-'a'];          }        node->istrue = 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 searchNode(word, root);    }        bool searchNode(string word, TrieNode* root)    {        if(!root)  return false;        if(word.length() == 0)  return root->istrue;        char c = word[0];        if(c == '.')        {            for(int i = 0; i < 26; i++)            {                if(root->children[i])                {                    if(searchNode(word.substr(1), root->children[i]))                        return true;                }            }        }        else if(root->children[c-'a'])        {            if(searchNode(word.substr(1), root->children[c-'a']))                return true;        }        return false;    }};


0 0
原创粉丝点击