真不容易。不靠debug写出来的。纸上分析的时候,写下i和j为两行,然后一个一个的写下改变的值,这样可以找到bug。
#include <cstring>
#include <malloc.h>
using namespace std;
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int needle_len = strlen(needle);
int haystack_len = strlen(haystack);
if (needle_len == 0) return haystack;
if (haystack_len == 0) return 0;
char* next = new char[needle_len];
getNext(needle, next, needle_len);
int i = 0;
int j = 0;
while (j < needle_len && i < haystack_len)
{
if (j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
free(next);
if (j == needle_len)
return haystack+i-j;
else
return 0;
}
void getNext(char *needle, char * next, int len) {
if (len == 0) return;
int i = 0;
int k = -1;
next[0] = -1;
while (i < len - 1)
{
if (k == -1|| needle[i] == needle[k]) {
i++;
k++;
next[i] = k;
}
else {
k = next[k];
}
}
}
};
python3,简单的双指针循环
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
for i in range(len(haystack)):
if (i + len(needle)) <= len(haystack):
flag = True
for j in range(len(needle)):
if haystack[i + j] != needle[j]:
flag = False
break
if flag:
return i
return -1