单词的添加与查找-LintCode
2017-10-20 18:41
357 查看
设计一个包含下面两个操作的数据结构:addWord(word), search(word)
addWord(word)会在数据结构中添加一个单词。而search(word)则支持普通的单词查询或是只包含.和a-z的简易正则表达式的查询。
一个 . 可以代表一个任何的字母。
注意事项:
你可以假设所有的单词都只包含小写字母 a-z。
样例:
addWord(word)会在数据结构中添加一个单词。而search(word)则支持普通的单词查询或是只包含.和a-z的简易正则表达式的查询。
一个 . 可以代表一个任何的字母。
注意事项:
你可以假设所有的单词都只包含小写字母 a-z。
样例:
addWord("bad") addWord("dad") addWord("mad") search("pad") // return false search("bad") // return true search(".ad") // return true search("b..") // return true
#ifndef C473_H #define C473_H #include<iostream> #include<string> using namespace std; class WordDictionaryNode{ public: WordDictionaryNode *child[26]; bool isWord; WordDictionaryNode() { this->isWord = false; for (auto &c : child) c = NULL; } }; class WordDictionary { public: /* * @param word: Adds a word into the data structure. * @return: nothing */ WordDictionary() { root = new WordDictionaryNode(); } void addWord(string &word) { // write your code here WordDictionaryNode *p = root; for (auto c : word) { int i = c - 'a'; if (!p->child[i]) p->child[i] = new WordDictionaryNode(); p = p->child[i]; } p->isWord = true; } /* * @param word: A word could contain the dot character '.' to represent any one letter. * @return: if the word is in the data structure. */ bool search(string &word) { // write your code here return searchRecur(word, root,0); } bool searchRecur(string &word, WordDictionaryNode *p,int pos) { if (pos >= word.size()) return p->isWord; if (word[pos] == '.') { for (auto c : p->child) { if (c&&searchRecur(word, c, pos + 1)) return true; } return false; } else return p->child[word[pos] - 'a'] && searchRecur(word, p->child[word[pos] - 'a'], pos + 1); } private: WordDictionaryNode *root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern"); #endif
相关文章推荐
- [LintCode] Add and Search Word 添加和查找单词
- lintcode-473-单词的添加与查找
- Lintcode---单词的添加与查找
- Lintcode 单词的添加与查找
- 构造一个单词查找树,支持以下两个操作的数据结构: 添加和搜索,只包含字母a-z或.。
- [LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计
- lintcode---实现trie--单词的添加与查找
- [ACM] POJ 1035 Spell checker (单词查找,删除替换添加不论什么一个字母)
- [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
- 473 - 单词的添加与查找
- 查找两个文件中相同的单词stl
- 前端_添加批量删除查找2
- vim 精确匹配查找单词【转】
- [笔试] 查找兄弟单词(2012/5/6 百度实习笔试题)
- linux 在vi编辑器里面有一个查找某个单词
- fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h"
- fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h
- 查找一个字符串中每个单词的出现次数--Java
- vim 精确皮配查找单词
- python学习笔记-使用re模板在字符串中查找所有单词