Leetcode 28 - Implement strStr(): question
Leetcode 28 - Implement strStr(): question
我在提交 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]) {
并修复任何连锁问题。不过,我希望它能按原样工作。
相关文章:
- 有 strstr() 的 constexpr 版本吗?
- Leetcode 28 - Implement strStr(): question
- strstr 函数误打误打
- char*newx=p+strlen(str1);这将如何执行,因为strstr将返回指向另一个字符串的第一个匹配字符的
- C++String.h字符表截断不带strstr的单词
- 如何比较strstr(lpcwstr,char*);
- strstr 返回如何不是一个常数
- 在C MBED中使用strstr,打印结果
- 性能比较:strstr()与std::string::find()
- 如何修复对strstr没有匹配函数调用的问题
- 如何在 Java 中模拟'question mark(?)'类型泛型以C++?
- G++ strstr 说从常量字符 * 到字符 * 的转换无效
- 使用 strstr 的计数不正确
- 性能标准::strstr vs. 标准::字符串::查找
- strstr函数与2015年相比不起作用
- C++中strstr()函数的时间复杂度、空间复杂度和算法是什么
- 无法使 strstr() 工作
- strstr无法搜索八进制格式数据中的字符串
- Implement strstr
- 编码是否会影响 strstr() 的结果(和相关函数)