Leetcode 28 - Implement strStr(): question

Leetcode 28 - Implement strStr(): question

本文关键字:question strStr Implement Leetcode      更新时间:2023-10-16

我在提交 Leetcode 28 时遇到了一个错误,到目前为止,我还没有找到这个错误。我的代码适用于大多数测试用例,但我被诸如大海捞针="密西西比",针="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;
}

输入:"密西西比州"、"伊西普" 输出: -1 (ans = 10, j = 1(

该函数有几个缺点。

对于初学者来说,它应该声明为

std::string::size_type strStr( const std::string &haystack, const std::string &needle );

如果在第一个字符串中找不到第二个字符串,则该函数应像类 std::string 的所有类似成员函数一样返回std::string::npos

函数参数外壳是常量引用类型。

此 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;
}

它的输出是

问题是你在

if (haystack[i++] != needle[j]) {

从而阻止探索第二个潜在的匹配。尝试

if (haystack[i + j] != needle[j]) {

并修复任何连锁问题。不过,我希望它能按原样工作。