链接:LintCode 炼码
题解:
class Typeahead {
private:
struct Trie {
Trie() {
end = false;
}
std::unordered_map<char, Trie*> next;
bool end;
std::unordered_set<std::string> words;
};
void search_trie(Trie* cur, std::vector<std::string>& result) {
if (cur->end) {
for (auto& word : cur->words) {
result.push_back(word);
}
}
for (auto entry : cur->next) {
search_trie(entry.second, result);
}
}
void insert_trie(const std::string& word, const std::string& real_word) {
Trie* cur = _root;
for (auto& ch : word) {
if (cur->next.find(ch) == cur->next.end()) {
cur->next[ch] = new (std::nothrow)Trie;
}
cur = cur->next[ch];
}
cur->end = true;
cur->words.insert(real_word);
}
Trie* _root;
public:
/*
* @param dict: A dictionary of words dict
*/
Typeahead(unordered_set<string> dict) {
// do intialization if necessary
_root = new (std::nothrow)Trie;
for (auto& word : dict) {
insert_trie(word, word);
for (int i = 0; i < word.size(); ++i) {
for (int j = 1; i + j <= word.size(); ++j) {
insert_trie(word.substr(i, j), word);
}
}
}
}
/*
* @param str: a string
* @return: a list of words
*/
vector<string> search(string &str) {
// write your code here
vector<std::string> result;
Trie* cur = _root;
for (auto& ch : str) {
if (cur->next.find(ch) == cur->next.end()) {
return result;
}
cur = cur->next[ch];
}
search_trie(cur, result);
//result.erase(unique(result.begin(), result.end()), result.end());
std::unordered_set<std::string> tmp(result.begin(), result.end());
result.clear();
std::vector<std::string> real_res(tmp.begin(), tmp.end());
return real_res;
}
};