leetcode28

public class Solution {
    public int StrStr(string haystack, string needle) {
        return haystack.IndexOf(needle);
    }
}

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

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

 1 class Solution:
 2     def strStr(self, haystack: str, needle: str) -> int:
 3         n = len(haystack)
 4         m = len(needle)
 5         if m == 0:
 6             return 0
 7         if n == 0 or m > n:
 8             return -1
 9         if haystack == needle:
10             return 0
11         
12         i,j = 0,0
13         idx = i
14         while i < n and j < m:
15             if haystack[i] != needle[j]:
16                 i = idx + 1
17                 idx = i
18                 j = 0
19             else:
20                 if idx == -1:
21                     idx = i 
22                 i += 1
23                 j += 1
24             if j == m:
25                 return idx
26         return -1

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

原文地址:https://www.cnblogs.com/asenyang/p/6769687.html