题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
写一个函数,返回子串needle 首次匹配母串haystack时的下标,如果子串不在母串中,则返回-1
代码:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len_h = len(haystack)
len_n = len(needle)
if len_h < len_n :
return -1
else :
for i in range(len_h-len_n+1) : #遍历母串
flag = 0 #标记是否匹配
for j in range(len_n) : #遍历子串
if haystack[i+j] != needle[j] :
flag = 1
break
if flag == 0 :
return i
return -1
笔记:
题目有点不好理解。另外可能对时间精度要求不高,直接遍历就能AC。