题目:
实现 strStr():实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
思路:
思路比较简单,暴力法。
程序:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
length1 = len(haystack)
length2 = len(needle)
if length2 == 0:
return 0
if length1 == 0:
return -1
if length1 < length2:
return -1
index = 0
while index < (length1 - length2 + 1):
if haystack[index] == needle[0]:
if haystack[index : index + length2] == needle[:]:
return index
else:
index += 1
else:
index += 1
return - 1