【发布时间】: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