【发布时间】:2019-08-06 14:51:07
【问题描述】:
我在提交 Leetcode 28 时遇到了一个迄今为止我一直没有发现的错误。我的代码适用于大多数测试用例,但我对诸如 haystack = "mississippi", needle = "issip" 等场景感到困惑。
我尝试过调试,发现整个 haystack 字符串都被迭代了,它返回 -1 或未找到。它在每次出现“i”时找到的子字符串长度为 4、1、1。
int strStr(string haystack, string needle) {
if (needle.empty()) {
return 0;
}
if (haystack.empty() && !needle.empty()) {
return -1;
}
int i = 0, j = 0, ans = 0;
for (i; i < haystack.length(); i++) {
if (haystack[i] == needle[0]) {
j = 0;
ans = i;
for (j; j < needle.length(); j++) {
/*
if (haystack[i++] == needle[j]) {
continue;
}
else {
break;
}
*/
if (haystack[i++] != needle[j]) {
break;
}
}
if (j == needle.length()) {
return ans;
}
}
if (j == needle.length()) {
return ans;
}
}
return -1;
}
输入:“mississippi”、“issip” 输出:-1(ans = 10,j = 1)
【问题讨论】:
-
与您的问题无关,但您的第二个
if无缘无故地过于复杂。如果needle不为空,则无需再次检查。 -
也许您应该解释一下,为什么
haystack.find(needle)不是您问题的答案?您可能有人为的限制,但请列出它们。 -
你看到
haystack[i++]的副作用了吗?您是否看到它如何跳过您的for (i;...循环中的扫描规律?您对“整个 haystack 字符串进行迭代”的断言是错误的。 -
是的,限制是这样的,所以我想主要手动编写解决方案,除了非常简单的方法,例如 empty() 和 length()。另外,我没有重新格式化这个问题,所以会有冗余;我主要关心的是为什么会发生这个特定的错误。非常感谢!
标签: c++ string algorithm function strstr