【问题标题】:Finding longest word in a digital tree with recursion使用递归在数字树中查找最长的单词
【发布时间】:2015-11-01 16:19:20
【问题描述】:

我有一个简单的数字树定义如下:

class DTN {
  public:
    DTN () :
      is_word(false), word_to_here(""), children()
    {}
    DTN (bool iw, std::string wth) :
      is_word(iw), word_to_here(wth), children()
    {}
    bool                     is_word;
    std::string              word_to_here;
    Map<char,DTN>  children;
};

我在定义一个名为longest_word (const DTN& dtn) 的函数时遇到问题,该函数假设返回数字树中最长的单词,并带有迭代器和递归,如下所示:

std::string longest_word (const DTN& dtn) {
    std::string lw = dtn.word_to_here;
    for(auto s:dtn.children){
        if(s.second.is_word && lw.length()<s.second.word_to_here.length()){
            lw = longest_word(s.second);
        }
        longest_word(s.second);
    }
    return lw;
}

假设我们在数字树 DTN 中有三个单词:(ante, anteater, anthebellum),调用最长的单词(DTN) 会给我一个空字符串“”而不是“anthebellum”。有人可以指出我在最长字函数中做错了什么吗?使用实际代码将不胜感激,因为我的英语不好,代码对我来说更容易理解。提前致谢。

【问题讨论】:

  • 这看起来不够——儿童类型? NTN 与 DTN?
  • 很抱歉,我放错了课程,我正在更新正确的课程。

标签: c++


【解决方案1】:

longest_word 的算法完全错误。您应该检查所有孩子最长的单词并返回更长的单词。在孩子的循环完成之前,您不能返回。请注意,您的算法将始终返回第一个孩子。我什至不明白你为什么要在那里检查一个完整的单词......

我可以尝试编写正确的代码,但我觉得它对你没有用。我的建议是回到最简单的算法,比如在整数列表中找到最大数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2021-12-15
    • 2017-07-04
    相关资源
    最近更新 更多