【问题标题】:Which method of isSubstringOf() is more efficient?isSubstringOf() 的哪种方法更有效?
【发布时间】:2013-08-02 11:38:48
【问题描述】:

您能否看一下这 2 段实现相同结果的代码:

别人的解决方案:

bool hasSubstring(const char *word, const char *container) {

    if (container[0] == '\0' || word[0] == '\0')
        return false;

    for(int i = 0; container[i] != '\0'; i++) {

        bool foundNonMatch = false;
        for(int j = 0; word[j] != '\0'; j++) {

            if (container[i + j] != word[j]) {
                foundNonMatch = true;
                break;
            }

        }

        if (!foundNonMatch)
            return true;
    }

    return false;
}

我的解决方案:

bool isSubstringOf(string word, string container) {

    bool success = false;       

    // if either is empty, automatically return false 
    if (!word.empty() && !container.empty()) {

        // loop through the container and while not successful
        for (unsigned i = 0; i < container.size() && !success; i++) {

            // if the first letter of the word is found in the container...
            if (word.at(0) == container.at(i)) {                        

                success = true; // success is temporarily true

                // loop through the word to make sure it exists in the container
                for (unsigned j = 1; j < word.size(); j++) {

                    // if either a mismatch happens, or container is too small
                    if (container.size() <= (j+i) || word.at(j) != container.at(j+i)) 
                        success = false;    // set the flag to false again

                }

            }
        }
    }

    return success;
}

哪一个使用更少的时间和复杂性?

据我了解,在最坏的情况下两者都是O(n^2),对吧?

【问题讨论】:

  • 你确定他们达到了同样的结果,例如对于空字符串?
  • @doctorlove 哦,是的,感谢您指出这一点,当任何一个字符串为“”时,它都返回 false。 “”包含“”是没有意义的。 "" 不包含任何内容。问题已更新
  • 后者可能会在每个循环中不断检查大小 - 如果幸运的话,它将被优化掉
  • “”包含“”是没有意义的——恰恰相反,它完全有道理。
  • 欢迎您提出自己的“包含”定义,不包括空字符串大小写。如果它对你有用,那就更好了(欢迎你在这里分享)。然而,这样的定义对其他人来说似乎不是很有用。随意检查任何现有的字符串或正则表达式库(其中有很多),或查阅任何计算机科学文本以了解“子字符串”的定义,或 look in the everyone's favourite source of knowledge

标签: c++ string algorithm substring std


【解决方案1】:

或者,与其重新发明轮子,不如使用:

container.find(word)

它来自标准库,因此您可以确信它具有合理的性能和正确性。您可以通过使用经过充分测试的已知构建块而不是自己动手来优化程序员时间、QA 时间、用户时间(而不是发布潜在的错误代码)。

【讨论】:

  • 谢谢,这是复习题之一,所以我觉得这将是一个有趣的练习 :)
  • 当然可以,自己试一试也无妨,看看有什么用,然后在生产代码中使用库函数:)。
【解决方案2】:

除非有明显的减速,否则仅通过查看两段代码是无法判断执行速度的。

大多数编译器都会优化您的代码,因此除非您喜欢研究操作码,否则很难判断哪个会更快预编译。

速度而言,您应该对代码进行基准测试。给它施加压力,看看它的表现如何。

效率不仅仅与速度有关。您还应该考虑哪一种适合您的编码风格。就个人而言,我讨厌看到随机的块,你甚至可以在研究它们被复制粘贴的代码之前就知道它们。

+ 改为在此处发布:codereview

【讨论】:

    【解决方案3】:

    它们都是二次的 - 在这两种情况下,容器的每个字母都会与每个单词的每个字母进行检查。
    既然你问了

    “时间和复杂性”

    一般来说无法回答。看看你的机器上哪个最快。

    【讨论】:

    • 它毕竟不属于这里。
    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 2013-06-05
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    相关资源
    最近更新 更多