28 Implement strstr()
题目不难,但是需要注意的地方很多。首先判断如果两个字符串长度不满足关系,可以直接返回。 不然进行双重循环,每次循环首先判断长度,然后进行匹配,如果都匹配不了,返回-1
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
target_length = len(needle)
pattern_length = len(haystack)
if pattern_length < target_length:
return -1
if target_length == 0:
return 0
for i in range(pattern_length):
start_position, end_position = i, i + target_length
if end_position > pattern_length:
return -1
f = True
for j in range(start_position, end_position):
if haystack[j] != needle[j-start_position]:
f = False
break
if f is True:
return i
return -1Copy
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) + 1):
for j in range(len(needle) + 1):
if j == len(needle):
return i
if i + j == len(haystack):
return -1
if needle[j]!=haystack[i + j]:
break