裸前缀树
题意:实现一个前缀树类,需要提供四个接口
- Trie():初始化对象
- void insert(String word):数据插入
- boolean search(String word):查询字符串是否存在
- boolean startsWith(String prefix):查询前缀是否满足
输入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
输出
[null, null, true, false, true, null, true]
解释
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 True
trie.search(“app”); // 返回 False
trie.startsWith(“app”); // 返回 True
trie.insert(“app”);
trie.search(“app”); // 返回 True
题解:通过26叉树实现
class Trie {
private:
vector<Trie*> children;
bool isEnd;
Trie* searchPrefix(string prefix) {
Trie* node = this;
for (char ch : prefix) {
ch -= 'a';
if (!node->children[ch])
return nullptr;
node = node->children[ch];
}
return node;
}
public:
Trie() : children(26), isEnd(false) {}
void insert(string word) {
Trie* node = this;
for (char ch : word) {
ch -= 'a';
if (!node->children[ch])
node->children[ch] = new Trie();
node = node->children[ch];
}
node->isEnd = true;
}
bool search(string word) {
Trie* node = this->searchPrefix(word);
if (node && node->isEnd) return true;
return false;
}
bool startsWith(string prefix) {
Trie* node = this->searchPrefix(prefix);
if (node) return true;
return false;
}
};
前缀树+DFS
题意:给出若干字符串,找出其中所有连接词(由2个及以上的字符串组合而成);
输入:words = [“cat”,“cats”,“catsdogcats”,“dog”,“dogcatsdog”,“hippopotamuses”,“rat”,“ratcatdogcat”]
输出:[“catsdogcats”,“dogcatsdog”,“ratcatdogcat”]
解释:“catsdogcats” 由 “cats”, “dog” 和 “cats” 组成;
“dogcatsdog” 由 “dog”, “cats” 和 “dog” 组成;
“ratcatdogcat” 由 “rat”, “cat”, “dog” 和 “cat” 组成。
题解:
struct Trie {
bool isEnd;
vector<Trie*> children;
Trie() {
children = vector<Trie*>(26);
isEnd = false;
}
};
class Solution {
public:
Trie *trie = new Trie();
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
vector<string> ret;
sort(words.begin(), words.end(), [&](const string & a, const string & b){
return a.length() < b.length();
});
for (string &word : words) {
if (word.empty())
continue;
if (dfs(word, 0))
ret.push_back(word);
else insert(word);
}
return ret;
}
bool dfs(const string &word, int start) {
if (word.length() == start)
return true;
Trie *node = trie;
for (int i = start; i < word.size(); i++) {
int index = word[i] - 'a';
node = node->children[index];
if (!node)
return false;
if (node->isEnd) {
if (dfs(word, i + 1))
return true;
}
}
return false;
}
void insert(const string & word) {
Trie *node = trie;
for (int i = 0; i < word.size(); i++) {
int index = word[i] - 'a';
if (!node->children[index])
node->children[index] = new Trie();
node = node->children[index];
}
node->isEnd = true;
}
};