isSubstringOf()的哪种方法更有效

Which method of isSubstringOf() is more efficient?

本文关键字:方法 有效 isSubstringOf      更新时间:2023-10-16

你能看看这两段实现相同结果的代码吗:

其他人的解决方案:

bool hasSubstring(const char *word, const char *container) {
    if (container[0] == '' || word[0] == '')
        return false;
    for(int i = 0; container[i] != ''; i++) {
        bool foundNonMatch = false;
        for(int j = 0; word[j] != ''; 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),对吧?

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

container.find(word)

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

您不能仅仅通过查看两段代码来判断执行速度的任何差异,除非有明显的速度减慢。

大多数编译器都会优化你的代码,因此,除非你喜欢研究操作码,否则判断哪一个更快的预编译并不容易。

速度而言,您应该对代码进行基准测试。强调它,看看它的表现如何。

效率并不完全取决于速度。您还应该考虑哪一个适合您的编码风格。就我个人而言,我讨厌看到随机的chunck,你甚至在研究代码之前就知道它们是复制粘贴的。

+改为张贴在那里:codereview

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

"时间和复杂性"

这不能笼统地回答。看看你的机器上哪一个最快。