个人思路:用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 = s