請你看看這2個代碼,實現同樣的結果:isSubstringOf()的哪個方法更高效?
別人的解決方案:
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
@doctorlove哦,是的,謝謝你指出,這意味着當任何字符串是「」時返回false。 「」包含「」沒有意義。 「」什麼都沒有。問題更新 – Oleksiy
後者可能會繼續檢查每個循環中的大小 - 如果你運氣好的話,它將被優化掉 – doctorlove