字典树
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
字典树的性质:
- 根节点不包含字符,除根节点外每一个节点都只包含一个字符
- 从根节点到某一个节点,路径上经过的字符连接起来,就是该节点对应的字符串
- 每个节点的所有子节点包含的字符都不相同。
LeetCode208. 实现 Trie (前缀树)
实现一个 Trie (前缀树),包含 insert
, search
, 和 startsWith
这三个操作。
示例
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
此题的目的就是了解字典树的基本操作,完整代码如下:
class Trie{
public:
struct Node{
bool isWord = false;
string word; // 加入存储单词节点
Node* next[26];
};
Node* root;
Trie(){
this->root = new Node();
}
//插入
void insert(string word){
Node* prefix = root;
for(int i = 0; i < word.size(); i++){
if(prefix->next[word[i] - 'a'] == nullptr)
prefix->next[word[i] - 'a'] = new Node();
prefix = prefix->next[word[i] - 'a'];
}
if(!prefix->isWord){
prefix->isWord = true;
prefix->word = word;
}
}
//搜索
bool search(string word){
Node* prefix = root;
for(char ch : word){
if(prefix->next[ch - 'a'] == nullptr)
return false;
prefix = prefix->next[ch - 'a'];
}
return prefix->isWord;
}
//前缀是否匹配
bool startsWith(string word){
Node* prefix = root;
for(char ch : word){
if(prefix->next[ch - 'a'] == nullptr)
return false;
prefix = prefix->next[ch - 'a'];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
LeetCode212. 单词搜索2
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
此题的核心是用回溯思想做,但是如果在LeetCode79-单词搜索1的基础上加一个循环,暴力解决的话,会出现超时,因此需要对算法的时间复杂度进行优化,于是我们引入了字典树的来优化单词存储遍历的方式,套用LeetCode-208的字典树模板代码完成,完整代码如下:
class Trie{
public:
struct Node{
bool isWord = false;
string word; // 加入存储单词节点
Node* next[26];
};
Node* root;
Trie(){
this->root = new Node();
}
void insert(string& word){
Node* prefix = root;
for(int i = 0; i < word.size(); i++){
if(prefix->next[word[i] - 'a'] == nullptr)
prefix->next[word[i] - 'a'] = new Node();
prefix = prefix->next[word[i] - 'a'];
}
if(!prefix->isWord){
prefix->isWord = true;
prefix->word = word;
}
}
};
class Solution {
private:
int row, column;
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
vector<vector<bool>> visited;
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
// DFS+Trie优化
vector<string> res;
row = board.size();
if(row == 0)
return res;
column = board[0].size();
if(column == 0)
return res;
Trie* T = new Trie();
for(string &word: words){
T->insert(word);
}
visited = vector<vector<bool>>(row, vector<bool>(column, false));
// DFS
for(int i = 0; i < row; ++i){
for(int j = 0; j < column; ++j){
Trie::Node* prefix = T->root;
if(prefix->next[board[i][j]-'a'] != nullptr)
dfs(board, i, j, prefix->next[board[i][j]-'a'], res);
}
}
return res;
}
private:
void dfs(const vector<vector<char>>& board, int i, int j, Trie::Node* prefix, vector<string>& res){
if(prefix->isWord){
if(count(res.begin(), res.end(), prefix->word)==0)
res.push_back(prefix->word);
}
visited[i][j] = true;
for(auto &d: dirs){
int x = i + d[0];
int y = j + d[1];
if((0 <= x && x < row && 0 <= y && y < column) && !visited[x][y] && prefix->next[board[x][y] - 'a']!=nullptr){
dfs(board, x, y, prefix->next[board[x][y] - 'a'], res);
}
}
visited[i][j] = false;
}
};