[leetcode] Add and Search Word - Data structure design
2015-06-13 16:15
549 查看
From : https://leetcode.com/problems/add-and-search-word-data-structure-design/
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
A
For example:
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-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
class WordDictionary { public: struct TrieNode { TrieNode *child[26]; bool isWord; TrieNode() : isWord(false) { for(auto &a : child) a = NULL; } }; WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode *p = root; for(auto &w : word) { if(!p->child[w-'a']) p->child[w-'a'] = new TrieNode(); p = p->child[w-'a']; } p->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 searchCore(word, root, 0); } bool searchCore(string &word, TrieNode* pre, int index) { if(index == word.size()) return pre->isWord; if(word[index] == '.') { for(auto &cur : pre->child) if(cur && searchCore(word, cur, index+1)) return true; return false; } else { TrieNode* cur = pre->child[word[index]-'a']; return cur && searchCore(word, cur, index+1); } } private: TrieNode *root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- 在浏览器输入网址到网页打开数据经过的过程
- shell学习十二天----行与字符串
- 机器学习中的相似性度量
- css小知识---input输入块
- js call
- UIBezierPath 的使用介绍
- Keil MDK中Image~~RW_IRAM1~~ZI~~Limit(~表示$)
- JQuery
- 使用WebRTC搭建前端视频聊天室——入门篇
- C++中的工厂模式(★好文章firecat推荐★)
- 1019. General Palindromic Number (20):郁闷了,深呼吸,做道题···
- OpenCV中GPU模块(CUDA)函数
- C++学习笔记之---输出一个数的八进制,十进制,十六进制
- 《代码之美》读后感
- Binary Tree Level Order Traversal
- Keiluversion4开发51和ARM环境的配置
- Binary Tree Level Order Traversal
- ASP.NET中Application全局对象用法实例浅析
- Redis介绍
- Codeforces Round #305 (Div. 2).D