62)实现前缀树
class Solution{
private:
bool isWord;
vector<Trie*> children;
Trie* isSearch(string word){
Trie* node = this;
for(const char& ch : word){
if(node->children[ch-'a'] == nullptr) return nullptr;
node = node->children[ch-'a'];
}
return node;
}
public:
Trie():isWord(false), children(26, nullptr){}
void insert(string word){
Trie* node = this;
for(const char& ch : word){
if(node->children[ch-'a'] == nullptr)
node->children[ch-'a'] = new Trie();
node = node->children[ch-'a'];
}
node->isWord = true;
}
bool search(string word){
Trie* node = this->isSearch(word);
return node!=nullptr && node->isWord;
}
bool startsWith(string prefix){
Trie* node = this->isSearch(prefix);
return node!=nullptr;
}
};
63)替换单词
class Solution {
public:
struct TrieNode{
string word;
TrieNode* children[26];
TrieNode(){
word = "";
memset(children, 0, sizeof(children));
}
};
vector<string> Split(string sentence){
stringstream ss(sentence);
string cur;
vector<string> res;
while(getline(ss, cur, ' ')){
if(!cur.empty()){
res.push_back(cur);
}
}
return res;
}
string replaceWords(vector<string>& dictionary, string sentence) {
TrieNode* root = new TrieNode();
for(auto& word : dictionary){
TrieNode* curr = root;
for(auto& ch : word){
if(curr->children[ch-'a']==nullptr){
curr->children[ch-'a'] = new TrieNode();
}
curr = curr->children[ch-'a'];
}
curr->word = word;
}
vector<string> words = Split(sentence);
string res;
for(auto word : words){
TrieNode* curr = root;
for(char ch : word){
if(curr->children[ch-'a']==nullptr) break;
else{
if(!curr->word.empty()) break;
curr = curr->children[ch-'a'];
}
}
if(!res.empty()) res += " ";
res += curr->word.empty() ? word : curr->word;
}
return res;
}
};
64)神奇的字典
class MagicDictionary {
public:
/** Initialize your data structure here. */
unordered_map<string, vector<string>> container;
MagicDictionary() {}
void buildDict(vector<string> dictionary) {
for(auto& word : dictionary){
auto str = word;
for(int i=0; i<str.size(); i++){
char c = word[i];
word[i] = '_';
container[word].push_back(str);
word[i] = c;
}
}
}
bool search(string searchWord) {
string e = searchWord;
for(int i=0; i<searchWord.size(); i++){
char ch = searchWord[i];
searchWord[i] = '_';
if(container.find(searchWord)!=container.end() && (container[searchWord].size()>1 || container[searchWord][0]!=e)) return true;
searchWord[i] = ch;
}
return false;
}
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dictionary);
* bool param_2 = obj->search(searchWord);
*/