首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Trie数据结构实现的错误

Trie数据结构实现的错误
EN

Stack Overflow用户
提问于 2015-12-11 00:12:09
回答 1查看 76关注 0票数 1

搜索功能中的错误是什么

代码语言:javascript
复制
search_word();

这个实现是否将效率时间复杂度用于Trie或不用于诸如插入/搜索之类的操作。假设一个1500个字母的字符串在不到2秒的时间内执行插入/搜索操作,它能被传递吗?

代码语言:javascript
复制
    class Trie
{
private:
     struct node
    {
        bool isWord;
        node* child[26];
        node()
        {
            for(int i = 0;i < 26;i++)
                child[i] = NULL;
            isWord = false;
        }
    };

    void insert_word(int index, node* vertex, int i, string s)
    {
        if(index == SZ)
        {
            vertex -> isWord = true;
             return;
        }
        int c = s[index] - 'a';
        if(vertex -> child[c] == NULL)
            vertex -> child[c] = new node;

        insert_word(index + 1, vertex -> child[c], c, s);

    }
    bool search_word(int index, node* vertex, int i, string s)
    {
        if(index == SZ && vertex -> isWord == true)
            return true;
        if(index == SZ && vertex -> isWord == false)
            return false;

        int c = s[index] - 'a';

        if(vertex -> child[c] == NULL)
            return false;
        else
            return search_word(index + 1, vertex -> child[c], c, s);
    }
public:
    int SZ;
    node* root;
    Trie()
    {
        root = new node;
    }
    void insert_word(string s)
    {
        SZ = s.size();
        insert_word(0, root, s[0] - 'a', s);
    }
    bool search_word(string s)
    {
        SZ = s.size();
      return search_word(0, root, s[0] - 'a', s);
    }

};

更新:发现了错误,代码必须正常工作。

EN

回答 1

Stack Overflow用户

发布于 2015-12-13 05:41:14

好了,我已经找到了这个bug,它在代码块中

代码语言:javascript
复制
  if(index == (SZ - 1))
    {
        vertex -> isWord = true;
         return;
    }

必须检查具有大小本身而不是大小的==的索引。?例如: string ab如果我们现在在字母b处处理,那么它的大小是否为== -1,这意味着字符串中的最后一个字符,代码将把它的词根标记为单词的结尾,而不是与字符b相关的节点,因为它从来没有通过编辑它来创建它的大小,它应该也可以在

代码语言:javascript
复制
search_word()

size -1也必须编辑

注意:我将更新问题本身,使其具有固定的代码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34206616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档