Add and Search Word - Data structure design - LeetCode
2015-11-09 08:04
411 查看
Design a data structure that supports the following two operations:
search(word) can search a literal word or a regular expression string containing only letters
For example:
Note:
You may assume that all words are consist of lowercase letters
思路:构建字典树。搜索时,若当前字符为'.',则将字典中当前位置存在的字符都搜索一遍。
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters
a-zor
.. A
.means it can represent any one letter.
For example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters
a-z.
思路:构建字典树。搜索时,若当前字符为'.',则将字典中当前位置存在的字符都搜索一遍。
class DictNode { public: DictNode *dict[27]; DictNode () { for (int i = 0; i < 27; i++) dict[i] = NULL; } }; class WordDictionary { public: WordDictionary() { root = new DictNode(); } // Adds a word into the data structure. void addWord(string word) { DictNode *cur = root; for (int i = 0, len = word.size(); i < len; i++) { int loc = (int)(word[i] - 'a'); if (cur->dict[loc] == NULL) cur->dict[loc] = new DictNode(); cur = cur->dict[loc]; } if (cur->dict[26] == NULL) cur->dict[26] = new DictNode(); } bool help(DictNode *cur, string word) { if (cur == NULL) return false; if (word.size() == 0) { if (cur->dict[26] == NULL) return false; return true; } if (word[0] != '.') { int loc = (int)(word[0] - 'a'); return help(cur->dict[loc], (word.size() > 1 ? word.substr(1) : "")); } else { for (int i = 0; i < 26; i++) if (cur->dict[i] != NULL) { if (help(cur->dict[i], (word.size() > 1 ? word.substr(1) : ""))) return true; } return false; } } // 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 help(root, word); } private: DictNode *root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- 机房重构之--七层架构
- BusyBox
- 编译静态二进制文件
- 小学生管理系统V1.0
- 每天一个linux命令(39):grep 命令
- Vector与ArrayList区别
- Java读取文件方法大全
- SQL Server 求结果
- 经方败案群20151103古求知讲“更年期综合征的治疗”语音整理版
- 5.3.3 32位颜色
- STL——空间配置器(SGI-STL)
- volatile,lock,synchronized
- Java记录 -71- HashMap源码剖析
- Implement Trie (Prefix Tree) - LeetCode
- 没有神话,聊聊decimal的“障眼法”
- 权重6老站SEO诊断,我的网站突破口在哪里?
- Directory Listing
- 昨天学习了汉诺塔递归,写了个显示移动的过程吧
- mysql - join two derived tables
- Leetcode NO.225 Implement Stack using Queues