C++ 实现字典树、插入、查找单词

C++ 实现字典树、插入、查找单词
在这里插入图片描述

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

//字典树结构体
struct TrieNode{
    bool isEnd;//判断此节点是否为单词结尾
    vector<TrieNode* >childNode;
    TrieNode():isEnd(0), childNode(26, NULL) {} //初始化列表构造函数  函数名与类名相同是构造函数
};

/**************************************************/
//向字典树中插入一个单词
void insert(TrieNode *root, const string word){
    TrieNode *temp=root;
    for(char i:word){
        //节点匹配,如果没有对应的字符,则需创建新的节点
        if(temp->childNode[i-'a'] == NULL) {
            temp->childNode[i-'a'] = new TrieNode();
        }
        temp = temp->childNode[i-'a'];//继续往下匹配
    }
    temp->isEnd = 1;//最后一个节点置1,表示它是一个单词的末尾
}

/**************************************************/
//查找一个单词
bool search(TrieNode *root, const string word) {
    TrieNode *temp=root;
    for(char i:word){
        temp=temp->childNode[i-'a'];//取单词中的每个字符进行判断
        if(!temp) break;
    }
    return temp?temp->isEnd:0;
}

//查找是否有以prefix为前缀的单词
bool startsWith(TrieNode *root, const string prefix) {
    TrieNode* temp = root;
    for(char i:prefix){
        temp=temp->childNode[i-'a'];//取单词中的每个字符进行判断
        if(!temp) return false;
    }
    return true;
}

int main() {

    TrieNode *root = new TrieNode();//新建节点
    insert(root, "word");
    cout<<search(root, "word")<<endl;
    cout<<startsWith(root, "a")<<endl;
    return 0;
}

参考:
Trie Tree 的实现 (适合初学者)🌳 - 实现 Trie (前缀树) - 力扣(LeetCode)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值