【问题标题】:Trie data structure implementaion's bugTrie 数据结构实现的 bug
【发布时间】:2016-03-16 08:49:09
【问题描述】:

搜索功能有什么问题

search_word();

并且此实现是否使用 Trie 的效率时间复杂度或不用于插入/搜索等操作。 考虑在不到 2 秒的时间内执行插入/搜索操作的 1500 个字母的字符串,可以通过吗?

    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);
    }

};

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

【问题讨论】:

    标签: c++ string data-structures trie


    【解决方案1】:

    好吧,我发现了这个错误,它在代码块中

      if(index == (SZ - 1))
        {
            vertex -> isWord = true;
             return;
        }
    

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

    中正常工作
    search_word()
    

    大小 - 1 也必须编辑

    注意:我将更新问题本身以获得固定代码。

    【讨论】:

      猜你喜欢
      • 2011-04-30
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多