查找字典中具有某个公共前缀的所有单词

本文介绍了一种使用C++实现的Trie数据结构,详细解释了其内部实现原理,并通过实例展示了如何利用Trie结构进行单词查找、前缀查找等操作。

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

## Trie.h ##
#include<set>
#include<string>

#define BRANCH  26
using namespace std;
struct  Node
{
    Node * next[BRANCH];
    int prefix;   //此前缀的单词个数
    bool isStr;
    Node() : prefix(0), isStr(false)
    {
        memset(next, 0, sizeof(next));

    }

};
class Trie
{
private:
    Node * root;
    set<string> *preSet;

    void DFS(Node * ptr, string preStr)
    {
        for (int i = 0; i < BRANCH; ++i)
        {
            if (ptr->next[i] != NULL)
            {
                char chr[] = { 'a' + i, '\0' };
                DFS(ptr->next[i], preStr + string(chr));
            }

            if (ptr->isStr)  //如果存在当前前缀的单词
            {
                this->preSet->insert(preStr);
            }
        }
    }
    //释放next数组
    void freeNextArr(Node * ptr)
    {
        for (int i = 0; i < BRANCH; i++)
        {
            if (ptr->next[i] != NULL)
            {
                freeNextArr(ptr->next[i]);
            }
        }
        delete ptr;
    }


public:
    Trie()
    {
        root = new Node();
        preSet = new set<string>();

    }

    //插入一个单词;
    void insert(const char * word)
    {

        if (word == NULL)
        {
            return;
        }
        Node * ptr = root;

        while (*word)
        {
            if (ptr->next[*word - 'a'] == NULL)
            {
                ptr->next[*word - 'a'] = new Node();
            }
            ptr->prefix++;
            ptr = ptr->next[*word - 'a'];
            ++word;
        }

        ptr->isStr = true;
    }

    //find the location of the word

    Node* search(const char * word)
    {
        if (word == NULL)
        {
            return NULL;
        }
        Node* ptr = root;
        while (ptr&&*word)
        {
            ptr = ptr->next[*word - 'a'];
            ++word;

        }
        return ptr;
    }


    //find the common prefix word set

    set<string>* findCommonPrefix_set(const char * prefix)
    {
        if (prefix == NULL)
        {
            return NULL;
        }

        Node* ptr = search(prefix);  //find the loication of prefix
        if (ptr == NULL)
        {
            return NULL;
        }
        DFS(ptr, string(prefix));


        return this->preSet;
    }


    //clear the preSet
    void clearPreSet()
    {
        this->preSet->clear();
    }


    //free the memory
    void freeMemory()
    {
        this->freeNextArr(root);
        delete this->preSet;

    }

};

## 测试程序 ##
#include<iostream>
#include "Trie.h"
void main()
{
    Trie comPreTrie;
    comPreTrie.insert("abc");
    comPreTrie.insert("abcd");
    comPreTrie.insert("abcde");
    comPreTrie.insert("abcdef");
    comPreTrie.insert("abcdefg");
    comPreTrie.insert("cde");



    /*test the common prefix "abcd"
    * 注:测试时输入合法字符,即a-z;
    *本文程序不会做出检查
    */


    Node* ptr = comPreTrie.search("abcd");

    if (ptr)
    {
        printf("num of words prefix by \"abcd\" is %d\n", ptr->isStr ? ptr->prefix + 1 : ptr->prefix);
    }
    else
    {
        printf("ptr for \"abcd\" is null");
    }

    set<string> *comPreSet = comPreTrie.findCommonPrefix_set("abcd");
    if (comPreSet)

    {
        for (set<string>::iterator it = comPreSet->begin(); it != comPreSet->end();++it)
        {
            printf("%s\n", (*it).c_str());
        }

    }
    else
    {
        printf("comPreSet for \"abcd\" is null");
    }
    comPreTrie.clearPreSet();
    printf("--------------------------------\n");

    ptr = comPreTrie.search("word");
    if (ptr)
    {
        printf("num of words prefix by \"word\" is %d\n",
            ptr->isStr ? ptr->prefix + 1 : ptr->prefix);
    }
    else
    {
        printf("ptr for \"word\" is null\n");
    }

    comPreSet = comPreTrie.findCommonPrefix_set("word");
    if (comPreSet)
    {
        for (set<string>::iterator it = comPreSet->begin();
            it != comPreSet->end(); ++it)
        {
            printf("%s\n", (*it).c_str());
        }
    }
    else
    {
        printf("comPreSet for \"word\" is null\n");
    }
    comPreTrie.clearPreSet();

    // free memory
    comPreTrie.freeMemory();
}
## 运行结果 ##

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值