很久没刷题,再次面对trie居然没有第一时间想起来
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-z
or .
. 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
.
第一份代码 用vector存储在一次比较果断timeout
#include <vector>
#include <string>
#include <algorithm>
using std::vector;
using std::string;
class WordDictionary {
vector<string> vec;
public:
// Adds a word into the data structure.
void addWord(string word) {
vec.push_back(word);
}
// 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) {
vector<string>::iterator iter;
iter = find_if(vec.begin(),vec.end(),[=](string str)
{
return [=](string l,string r)
{
size_t pos = l.size();
if (pos != r.size()) return false;
for (int i =0;i != pos;++i){
if (l[i] != r[i] && l[i] != '.') return false;
}
return true;
}(word,str);
});
if (iter != vec.end()){
return true;
}
return false;
}
};
#include <vector>
#include <string>
#include <algorithm>
using std::vector;
using std::string;
class WordDictionary {
struct trie
{
struct trie * next[26];
bool end;
};
struct trie * root;
void creat(struct trie *&root)
{
root = new struct trie;
root->end = false;
memset(root->next,0,sizeof root->next);
}
bool search(string word,struct trie * root)
{
// word is not end
if (root == NULL) return false;
size_t len = word.size();
for (int i =0;i!=len;++i){
size_t pos = word[i] - 'a';
if (word[i] != '.'){
if (root->next[pos] == NULL) return false;
root = root->next[pos];
}else{
// word[i] is . ,so we should handle it
for (int k =0;k!=26;++k){
if (search(word.substr(i+1),root->next[k])) return true;
}
return false;
}
}
return root->end;
}
public:
WordDictionary()
{
creat(root);
}
~WordDictionary(){delete root;}
// Adds a word into the data structure.
void addWord(string word) {
struct trie * temp = this->root;
//struct trie * next = temp;
for_each(word.begin(),word.end(),[&](char c)
{
size_t pos = c- 'a';
if (temp->next[pos] == NULL){
creat(temp->next[pos]);
}
temp = temp->next[pos];
});
temp->end = 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 search(word,root);
}
};
int main()
{
WordDictionary wordDictionary;
wordDictionary.addWord("ab");
wordDictionary.search("a.");
}