中级农民
- 积分
- 138
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-9-7
- 最后登录
- 1970-1-1
|
这个应该就是LC211的扩展了,加上了support for '*'. 关键是当search word遇到'*',要跳过所有可能连续的'*'继续寻找下一个非'*'的char。在字典数据结构的Trie中就对于找当前node的所有对应的子孙nodes(若是'.'就找所有子孙)。然后再循环每个子孙node递归。一个edge case就是若word以连续的'*'结尾的话就直接返回true,因为'*'之前的prefix在字典中已经找到了。
大家看看code有没有问题。- struct Nd { // Trie node for dictionary
- bool flag; // true if representing a word
- vector<Nd*> next;
- Nd():flag(false),next(vector<Nd*>(26)) {}
- };
-
- class WordDictionary {
- private:
- Nd* r; // dummy root for Trie
-
- // get all nodes from descendants of cur representing as char c;
- // if c is not alphabet, get all descendants
- void getNodes(Nd* cur, char c, vector<Nd*>& nodes) {
- if (!cur) return;
- int ic = c - 'a';
- for (int i = 0; i < 26; ++i) {
- if (!cur->next[i]) continue;
- if (ic == i || ic < 0 || ic >= 26)
- nodes.push_back(cur->next[i]);
- getNodes(cur->next[i], c, nodes);
- }
- }
-
- // search word w from index start
- bool mySearch(string w, int start, Nd* cur) {
- if (!cur) return false;
- int n = w.length();
- if (start == n) return cur->flag;
- else if (start > n) return false;
-
- char c = w[start];
- if (c >= 'a' && c <= 'z') { // c is alphabet
- return mySearch(w, start+1, cur->next[c-'a']);
- }else if (c == '.') { // c is '.'
- for (int i = 0; i < 26; i++) {
- if (mySearch(w, start+1, cur->next[i])) return true;
- }
- return false;
- }else { // c is '*'
- // find next non '*' char and store it in c
- while (++start < n && (c=w[start]) == '*') continue;
- if (start == n) return true; // all trailing '*''s
- // get all nodes from descendants of cur representing as char c;
- // otherwise c is '.', and so get all descendants
- vector<Nd*> nodes; getNodes(cur, c, nodes);
- for (auto node : nodes) {
- if (mySearch(w, start, node)) return true;
- }
- return false;
- }
- }
-
- public:
- // constructor
- WordDictionary() { r = new Nd(); }
- // Adds a word into the data structure.
- void addWord(string word) {
- Nd* cur = r;
- for (char c:word) {
- int i = c-'a';
- if (!cur->next[i]) cur->next[i] = new Nd();
- cur = cur->next[i];
- }
- cur->flag = true;
- }
- // Returns if the word is in the data structure. Support '.' and '*'
- bool search(string word) { return mySearch(word, 0, r); }
- };
复制代码 |
|