个人思路:用KMP算法,从跳过每次匹配成功的部分
感觉写出来的代码怪怪的,虽然能通过,但是比题解少很多
python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(haystack)
n = len(needle)
if m < n:
return -1
for i in range(0, m):
j = 0
while(j < n):
if haystack[i] == needle[j]:
i += 1
j += 1
if i >= m:
break
else:
break
if j == n:
return i - n
else:
i = i + j
return -1
C:官方题解代码,按理说应该需要保存前缀函数值,但python这套运行逻辑放在C上就无法运行,蛮奇怪的
int strStr(char* haystack, char* needle) {
int n = strlen(haystack), m = strlen(needle);
if (m == 0) {
return 0;
}
int pi[m];
pi[0] = 0;
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle[i] != needle[j]) {
j = pi[j - 1];
}
if (needle[i] == needle[j]) {
j++;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = pi[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}