LeetCode(211) Add and Search Word - Data structure design

来源:互联网 发布:淘宝女装店铺素材 编辑:程序博客网 时间:2024/05/12 18:20

用递归来实现递推

class TrieNode {public:    int val;    TrieNode *children[26];    // Initialize your data structure here.    TrieNode() {        val = 0;        for (int i=0; i < 26; i++) children[i] = NULL;    }};class WordDictionary {public:    WordDictionary() {        root = new TrieNode();    }    WordDictionary(TrieNode *p) {        root = p;    }    // Adds a word into the data structure.    void addWord(string word) {        TrieNode *p = root;        for(int i = 0; i < word.size(); i++) {            if(p->children[word[i] - 'a'] == NULL)  p->children[word[i] - 'a'] = new TrieNode();            p = p->children[word[i] - 'a'];        }        p->val = 1;    }    // 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) {        if(word.size() == 1) {            TrieNode *p = root;            if(word[0] != '.') {                if(p->children[word[0] - 'a'] != NULL && (p->children[word[0] - 'a'])->val == 1) return true;                return false;            }else {                for(int j = 0; j < 26; j++) {                    if(p->children[j] != NULL && (p->children[j])->val == 1)                       return true;                }                return false;            }        }        TrieNode *p = root;        if(word[0] != '.') {            if(p->children[word[0] - 'a'] == NULL) return false;            WordDictionary word3(p->children[word[0] - 'a']);            return word3.search(word.substr(1));        }else {            for(int j = 0; j < 26; j++) {                if(p->children[j] != NULL) {                    WordDictionary word2(p->children[j]);                    if(word2.search(word.substr(1))) return true;                }            }            return false;        }    }public:    TrieNode* root;};// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary;// wordDictionary.addWord("word");// wordDictionary.search("pattern");
0 0
原创粉丝点击