28. Implement strStr()

题目

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

题意

实现字符串匹配,这里我用的时两重循环解决,当然有更好的算法,如KMP

Python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len1=len(haystack)
len2=len(needle)
if len2==0 :return 0
if len1==0 :return -1
for i in range(len1):
k=0
while k+i<len1 and k<len2 and haystack[k+i]==needle[k]:k+=1
if k==len2:return i
if k+i==len1:return -1
i+=1
return -1
如果觉得有帮助,给我打赏吧!