这个题目有两种比较常用的方法,一种是暴力解法,时间复杂度是O(mn),一种是KMP算法,由于KMP算法一般都是ACM竞赛才会使用到,因此这里这里只提供Python的暴利解法。
题目如下:
![](https://i-blog.csdnimg.cn/blog_migrate/29649c5a67b591e67d63c67ffbfe6d73.jpeg)
使用Python暴利解答的代码如下:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(haystack)==0 and len(needle)==0:
return 0
if haystack==None and needle==None:
return 0
else:
if needle in haystack:
return haystack.index(needle)
else:
return -1