208 思路:字典树实现
//字典树定义
struct Node {
Node *next[26];
bool value;
Node(): value(false) {
for (auto &a : next) a = nullptr;
}
};
class Trie {
public:
//头节点
Node *root = new Node();
//插入,root不进行操作
void insert(string word) {
Node* temp = root;
for (int i = 0; i < word.size(); i++) {
int key = word[i] - 'a';
if (!temp->next[key]) {
temp->next[key] = new Node();
}
temp = temp->next[key];
}
temp->value = true;
}
//查找
bool search(string key) {
Node* temp = root;
for (int i = 0; i < key.size(); i++) {
if (temp->next[key[i] - 'a']) {
temp = temp->next[key[i] - 'a'];
} else {
return false;
}
}
return temp->value;;
}
//前缀树匹配,不一定是一个单词,故需要在中间进行判断
bool startsWith(string prefix) {
Node* temp = root;
for (int i = 0; i < prefix.size(); i++) {
if (temp->next[prefix[i] - 'a']) {
temp = temp->next[prefix[i] - 'a'];
} else {
return false;
}
}
return true;
}
};
211 思路:字典树 + DFS,小数点可以匹配各种字母,故需要26个字母全部遍历,符合DFS
struct Node {
Node* next[26];
bool value;
Node() {
for (int i = 0; i < 26; i++) {
next[i] = nullptr;
}
value = false;
}
};
class WordDictionary {
public:
Node* root = new Node();
WordDictionary() {
root = new Node();
}
void addWord(string word) {
Node* temp = root;
for (int i = 0; i < word.size(); i++) {
if (!temp->next[word[i] - 'a']) {
temp->next[word[i] - 'a'] = new Node();
}
temp = temp->next[word[i] - 'a'];
}
temp->value = true;
}
//DFS进行遍历查找
void dfs(Node* root, string word, bool& res, int idx) {
if (idx >= word.size()) {
if (idx == word.size() && root->value) {
res = true;
}
return;
}
for (int i = idx; i < word.size(); i++) {
//非小数点匹配
if (word[i] != '.') {
if (root->next[word[i] - 'a']) {
dfs(root->next[word[i] - 'a'], word, res, i + 1);
}
} else {
//小数点匹配逻辑
for (int j = 0; j < 26; j++) {
if (root->next[j]) {
dfs(root->next[j], word, res, i + 1);
}
}
}
//其他情况直接return
return;
}
}
bool search(string word) {
bool res = false;
dfs(root, word, res, 0);
return res;
}
};