前缀树的实现

前缀树的实现

何谓前缀树?

前缀树(字典树),使用树状的数据结构存储一个字典的所有单词。前缀树是一个多叉树,一个节点可能有多个子节点,除根结点外,每个节点代表字符串中的一个字符。字符串在前缀树中不一定终止于叶子节点,比如 'app'。如果前缀树路径到达某个节点时表示了一个完整的字符串,那么这个节点应有特殊的标识。一个存储字符串 "apple" "apply" "app" "huw" "oppo" "xiao" "mi" 的前缀树如图:

实现前缀树

实现一个前缀树 Trie ,它有下列操作:

  1. 函数 insert ,在前缀树中添加一个字符串
  2. 函数 search,查找字符串,如果前缀树中包含该字符串则返回 true,否则返回 false。
  3. 函数 startWith,查找字符串前缀。

节点的选择

子节点容器可以选择使用哈希表或数组。

  • 在字符集大小固定且较小的情况下,数组可以提供紧凑的存储,没有额外的哈希表开销。数组可以保持元素有序性以及空间效率比较高。
  • 哈希表比较灵活。

真实的结构:

cpp 复制代码
class TrieNode {
public:
	std::unordered_map<char, TrieNode*> children;
	bool id_end_of_word;
	
	TrieNode() : is_end_of_word(false) {}
};

插入

cpp 复制代码
 void insert(const std::string& word) {
     TrieNode* node = root;
     for (char ch : word) {
         if (node->children.find(ch) == node->children.end()) {
             node->children[ch] = new TrieNode();
         }
         node = node->children[ch];
     }
     node->isEndOfWord = true;
 }

查找

cpp 复制代码
bool search(const std::string& word) {
	TrieNode* node = root;
	for (const auto& ch : word) {
		if (node->children.find(ch) == node->children.end()) return false;
		node = node->children[ch];
	}
	return node->is_end_of_word;
}

查找前缀

查找前缀与查找差别在于:可以直接返回 true。

cpp 复制代码
bool startWith(const std::string& word) {
	TrieNode* node = root;
	for (const auto& ch : word) {
		if (node->children.find(ch) == node->children.end()) return false;
		node = node->children[ch];
	}
	return true;
}

完整代码

cpp 复制代码
class Trie {
private:
    TrieNode* root;
    
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(const std::string& word) {
        TrieNode* node = root;
        for (char ch : word) {
            if (node->children.find(ch) == node->children.end()) {
                node->children[ch] = new TrieNode();
            }
            node = node->children[ch];
        }
        node->isEndOfWord = true;
    }
    
    bool search(const std::string& word) const {
        TrieNode* node = root;
        for (char ch : word) {
            if (node->children.find(ch) == node->children.end()) {
                return false;
            }
            node = node->children[ch];
        }
        return node->isEndOfWord;
    }
};
相关推荐
阿客不是客7 分钟前
深入计算机语言之C++:C到C++的过度
c++
LN-ZMOI14 分钟前
c++学习笔记1
c++·笔记·学习
数据分析螺丝钉17 分钟前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games17 分钟前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
￴ㅤ￴￴ㅤ9527超级帅18 分钟前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
五味香18 分钟前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
PYSpring39 分钟前
数据结构-LRU缓存(C语言实现)
c语言·数据结构·缓存
毕小宝42 分钟前
逻辑回归(下): Sigmoid 函数的发展历史
算法·机器学习·逻辑回归
小叮当爱咖啡1 小时前
DenseNet算法:口腔癌识别
算法
希望有朝一日能如愿以偿1 小时前
算法(食物链)
算法