leetcode28

时间:2023-03-09 15:35:57
leetcode28
public class Solution {
public int StrStr(string haystack, string needle) {
return haystack.IndexOf(needle);
}
}

https://leetcode.com/problems/implement-strstr/#/description

python实现,不实用内置函数:

 class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
if m == :
return
if n == or m > n:
return -
if haystack == needle:
return i,j = ,
idx = i
while i < n and j < m:
if haystack[i] != needle[j]:
i = idx +
idx = i
j =
else:
if idx == -:
idx = i
i +=
j +=
if j == m:
return idx
return -

作为一道easy题目,提交成功率只有33%,可以看出本题的一些细节需要仔细分析,否则很容易出错。