leetcode + 前缀树(字典树)

本文介绍了一个Trie树(字典树)的C++实现。该实现支持字符串的插入、搜索及前缀匹配等功能。通过使用Trie树可以高效地处理字符串集合的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <vector>
#include <numeric>
#include <limits>
#include <math.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
using namespace std;
//每个节点有26个分之。
class Trie {
public:
    const int R=26;
    struct Node{
        bool is_word = false;
        Node *next = NULL;
    };
    Node root;
    /** Initialize your data structure here. */
    Trie() {
        
    }
    /** Inserts a word into the trie. */
    void insert(string word) {
        if(word.empty()) return;
        Node* x= &root;
        int p =0;
        while (p<word.size()) {
            if(!(x->next)) x->next = new Node[R]; //申请了26个R
            x = & x->next[word[p++]-'a'];
        }
        x->is_word = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Node x = root;
        int p = 0;
        while(x.next && p<word.size()){
            x = x.next[word[p++]- 'a'];
        }
        return p== word.size() && x.is_word;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Node x = root;
        int p =0;
        while (x.next && p<prefix.size()) {
            x = x.next[prefix[p++]-'a'];
        }
        return p==prefix.size() && (x.is_word || x.next);
    }
};
int main()
{
    Trie temple;
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值