LeetCode-211.Add and Search Word - Data structure design

来源:互联网 发布:人工智能危机作文 编辑:程序博客网 时间:2024/05/27 10:42

https://leetcode.com/problems/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.

显然这是一道Trie树的应用

关于Trie树的构造可以查看题 LeetCode-208.Implement Trie (Prefix Tree)

查找".ad"和"b.."等非完整词时,需要用到递归

class TrieNode{public:TrieNode *children[26];bool isWord;TrieNode(){isWord = false;for (auto &node : children)node = NULL;}};class WordDictionary {public:    WordDictionary(){root = new TrieNode();}    // Adds a word into the data structure.    void addWord(string word) {        TrieNode *node = root;for (char c : word){if (!node->children[c - 'a'])node->children[c - 'a'] = new TrieNode();node = node->children[c - 'a'];}node->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 search2(word, root);    }    private:TrieNode* root;bool search2(string word, TrieNode *pp){TrieNode *node = pp;for (char c : word){if (c == '.'){for (auto &p : node->children){if (!p)continue;if (search2(word.substr(1), p))return true;}return false;}else{if (!node->children[c - 'a'])return false;return search2(word.substr(1), node->children[c - 'a']);}}return node->isWord;}};// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary;// wordDictionary.addWord("word");// wordDictionary.search("pattern");


0 0
原创粉丝点击