我提交的Leetcode 28程序存在一个错误,到目前为止,这还使我难以理解。我的代码适用于大多数测试用例,但是我迷上了诸如haystack =“ mississippi”,needle =“ issip”这样的场景。
我尝试调试,发现整个干草堆字符串都经过遍历,并且返回-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)
答案 0 :(得分:2)
问题是您在
i中修改了 i
if (haystack[i++] != needle[j]) {
因此防止了第二次潜在比赛的进行。试试
if (haystack[i + j] != needle[j]) {
并解决所有连锁问题。我希望它能按原样工作。
答案 1 :(得分:2)
该功能有几个缺点。
对于初学者,应声明为
std::string::size_type strStr( const std::string &haystack, const std::string &needle );
,如果在第一个字符串中未找到第二个字符串,则该函数应返回std::string::npos
,与类std :: string的所有类似成员函数一样。
函数参数外壳为常量引用类型。
此if语句中的条件
if (haystack.empty() && !needle.empty())
具有冗余操作数。可以像
那样重写if (haystack.empty())
此循环
for (i; i < haystack.length(); i++)
当第一个字符串的尾部大小小于第二个字符串的大小时,应停止其迭代。
在此if语句中
if (haystack[i++] != needle[j]) {
变量i递增,导致变量两次递增:在此语句中一次递增,在循环中第二次递增。
第二对这些语句
if (j == needle.length()) {
return ans;
是多余的。
可以按照演示程序中所示的以下方式编写函数。
#include <iostream>
#include <string>
std::string::size_type strStr( const std::string &haystack, const std::string &needle )
{
if ( needle.empty() )
{
return 0;
}
else if ( haystack.empty() )
{
return -std::string::npos;
}
else
{
std::string::size_type ans = std::string::npos;
auto n1 = haystack.length();
auto n2 = needle.length();
for ( std::string::size_type i = 0; ans == std::string::npos && i + n2 <= n1; i++ )
{
std::string::size_type j = 0;
while ( j < n2 && haystack[i+j] == needle[j] ) j++;
if ( j == n2 ) ans = i;
}
return ans;
}
}
int main()
{
std::string haystack( "mississippi" );
std::string needle( "issip" );
std::cout << strStr( haystack, needle ) << '\n';
return 0;
}
其输出为
4