字典树TrieC++实现

字典树TrieC++实现

实现代码

#include<bits/stdc++.h>
using namespace std;

class Trie {
private:
    static const int MAX_SIZE = 1024;
    static const int SIGMA_SIZE = 26;
    int character[MAX_SIZE][SIGMA_SIZE];
    bool tag[MAX_SIZE];
    int size;
    int index(char c);
public:
    Trie();
    void insert(string str);
    bool search(string str);
};

Trie::Trie() {
    size = 1;
    memset(character[0], 0, sizeof(character[0]));
}

int Trie::index(char c) {
    return c - 'a';
}

void Trie::insert(string str) {
    int currentLevel = 0;
    for (int i = 0; i < str.size(); i++) {
        int c = index(str[i]);
        if (!character[currentLevel][c]) {
        	// 将新建节点的下一层清零, 若之后存在以当前已搜寻字符串子串公共前缀的可以迅速建立孩子节点,该层用于存放其所有孩子节点
            memset(character[size], 0, sizeof(character[size]));
            tag[size] = false;
            // 新建节点
            character[currentLevel][c] = size++;
        }
        // 跳转到其孩子节点所在的层搜寻
        currentLevel = character[currentLevel][c];
    }
    // 标记当前为结尾的字符串为字典树的一个单词
    tag[currentLevel] = true;
}

bool Trie::search(string str) {
    int currentLevel = 0;
    for (int i = 0; i < str.size(); i++) {
        int c = index(str[i]);
        if (!character[currentLevel][c]) {
        	// 若字符没有索引,则说明与搜索字符串不存在
            return false;
        }
        currentLevel = character[currentLevel][c];
    }
    //若对应tag为true则表示欲搜索的字符串是字典树Trie中存放的单词,否则表示存在一个字符串的前缀是欲搜索的这个字符串,但字典树Trie不存在这个单词
    return tag[currentLevel];
}

int main(int argc, char const *argv[])
{
    string str;
    Trie trie;
    while (cin >> str) {
        trie.insert(str);
        cin >> str;
        printf("%s\n", trie.search(str) ? "Exist" : "Not found");
    }
    return 0;
}

算法思路

  • 建立Trie
    根据输入字符串的顺序,若字符串的前缀已经存在于字典树中,则沿着对应的子树搜索,直到不匹配。不匹配时,新建节点插入字典树,不断循环,直到结束,将对应tag置为true表示这是一个存放在字典树中的单词
  • 搜索
    根据输入字符串的顺序,一次搜索,若字符串的前缀已经存在于字典树中,则沿着对应的子树搜索,若出现不匹配则返回false,否则返回tag,若tag为true则表示欲搜索的字符串是字典树Trie中存放的单词,否则表示存在一个字符串的前缀是欲搜索的这个字符串,但字典树Trie不存在这个单词
  • character数组
    存放的是字典树Trie当前结点的孩子节点所在的层的索引(层数,二维数组行标),其所有的孩子节点都该层中,数组的下标则对应相应的字符,根节点不对应任何字符

输入数据

eclipse
eclipse
ecs
cs
program
pro

输出结果

Exist
Not found
Not found

鸣谢

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值