您能否看看这两条实现相同结果的代码:
别人的解决方案:
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)
最坏的情况,对吧?