首页 > 代码库 > 一刷leetcode——数据结构
一刷leetcode——数据结构
211. Add and Search Word - Data structure design
题意:add函数插入单词形成词典,search函数查询有没有某单词,查询时“.”可以代表任何一个字母
我的思路:字典树+递归
我的代码:数组写法
class WordDictionary { public: /** Initialize your data structure here. */ int ch[40000][26], sz, val[40000]; WordDictionary() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); } /** Adds a word into the data structure. */ void addWord(string word) { int u = 0, n = word.size(); for (int i = 0; i < n; i++) { int c = word[i]-‘a‘; if (!ch[u][c]) { memset(ch[sz], 0, sizeof(ch[sz])); val[sz] = 0; ch[u][c] = sz++; } u = ch[u][c]; } val[u] = 1; } /** Returns if the word is in the data structure. A word could contain the dot character ‘.‘ to represent any one letter. */ bool query(int j, string word) { int n = word.size(); for (int i = 0; i < n; i++) { if (word[i] != ‘.‘) { j = ch[j][word[i]-‘a‘]; if (j == 0) return 0; } else { int flag = 1, k; for (k = 0; k < 26; k++) { if (ch[j][k]) { flag = 0; if (query(ch[j][k], word.substr(i+1, n-1-i))) return 1; } } if (flag || k == 26) return 0; } } if (val[j] == 1) return 1; return 0; } bool search(string word) { return query(0, word); } };
solution解法:字典树指针写法
class TrieNode { public: bool isKey; TrieNode* children[26]; TrieNode(): isKey(false) { memset(children, NULL, sizeof(TrieNode*) * 26); } }; void addWord(string word) { TrieNode* run = root; for (char c : word) { if (!(run -> children[c - ‘a‘])) run -> children[c - ‘a‘] = new TrieNode(); run = run -> children[c - ‘a‘]; } run -> isKey = true; } private: TrieNode* root; WordDictionary() { root = new TrieNode(); } class TrieNode { public: bool isKey; TrieNode* children[26]; TrieNode(): isKey(false) { memset(children, NULL, sizeof(TrieNode*) * 26); } }; class WordDictionary { public: WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* run = root; for (char c : word) { if (!(run -> children[c - ‘a‘])) run -> children[c - ‘a‘] = new TrieNode(); run = run -> children[c - ‘a‘]; } run -> isKey = 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 query(word.c_str(), root); } private: TrieNode* root; bool query(const char* word, TrieNode* node) { TrieNode* run = node; for (int i = 0; word[i]; i++) { if (run && word[i] != ‘.‘) run = run -> children[word[i] - ‘a‘]; else if (run && word[i] == ‘.‘) { TrieNode* tmp = run; for (int j = 0; j < 26; j++) { run = tmp -> children[j]; if (query(word + i + 1, run)) return true; } } else break; } return run && run -> isKey; } };
一刷leetcode——数据结构
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。