isSubstringOf()的哪种方法更有效?

时间:2013-08-01 13:48:30

标签: c++ string algorithm substring std

请你看看这两个代码得到相同的结果:

其他人的解决方案:

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),对吗?

3 个答案:

答案 0 :(得分:1)

或者,您可以使用:

,而不是重新发明轮子
container.find(word)

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

答案 1 :(得分:0)

除非有明显的减速,否则只能通过查看两段代码来判断执行速度是否存在差异。

大多数编译器都会优化你的代码,因此除非你喜欢研究操作码,否则说明哪一个编译速度会更快。

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

效率并非完全与速度有关。您还应该考虑哪种适合您的编码风格。就个人而言,我讨厌在你研究它们被复制粘贴的代码之前看到你可以告诉的随机组块。

+ 在那里发布:codereview

答案 2 :(得分:0)

它们都是二次的 - 在两种情况下,每个字的每个字母都会检查容器的每个字母。
既然你问过

  

“时间和复杂性”

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