字符串s构造前缀树,并判断p是否属于s的子串

1、描述

根据几个单词,构造一个前缀树,再给定一个单词p,判断p是否属于s的前缀
输入:vec = {“hello”, “world”, “hey”, “hi”} p = “hell”
输入:yes

2、notes

就直接构造

3、code

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

struct TrieNode {
    TrieNode* children[26];
    bool isEnd;

    TrieNode() {
        memset(children, 0, sizeof(children));
        isEnd = false;
    }
};

void insert(TrieNode* root, string word) {
    TrieNode* node = root;
    for (char c : word) {
        int index = c - 'a';
        if (!node->children[index]) {
            node->children[index] = new TrieNode();
        }
        node = node->children[index];
    }
    node->isEnd = true;
}

TrieNode* buildTrie(vector<string>& words) {
    TrieNode* root = new TrieNode();
    for (string word : words) {
        insert(root, word);
    }
    return root;
}

bool isPrefix(TrieNode* root, string prefix) {
    TrieNode* node = root;
    for (char c : prefix) {
        int index = c - 'a';
        if (!node->children[index]) {
            return false;
        }
        node = node->children[index];
    }
    return true;
}

int main() {
    vector<string> words = {"hello", "world", "hi", "hey"};
    TrieNode* root = buildTrie(words);

    string s = "hello, world, hi, hey";
    string p1 = "worldi";
    string p2 = "hell";
    string p3 = "abc";

    if (isPrefix(root, p1)) {
        cout << p1 << " is a prefix of " << s << endl;
    } else {
        cout << p1 << " is NOT a prefix of " << s << endl;
    }


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值