'''
實(shí)現(xiàn)字符串find
實(shí)現(xiàn)字符串的find函數(shù),返回字符串source中 子串target開始的位置, 從start索引開始搜索,如果可以找到多個(gè),返回第一個(gè),如果找不到返回-1
例子
my_find('this is a book', 'this') -> 0
my_find('this is a book', 'this', start=1) -> -1
假設(shè)
source,target一定為字符串類型
tips
樸素的兩重循環(huán)
'''
def my_find(source, target, start=0):
"""
返回字符串source中 子串target開始的位置, 從start索引開始搜索
如果可以找到多個(gè),返回第一個(gè)
:param source:
:param target:
:param start:
:return:
"""
#二重循環(huán)
len_source = len(source)
len_target = len(target)
if len_target == 0 or len_source == 0 or len_source < len_target:
return -1
for i in range(start, len_source):
for j in range(len_target):
if target[j] == source[i+j]:
j += 1
else:
break
if j == len_target:
return i
else:
i += 1
return -1
# pass
print(my_find('this is a book', 'this'))# -> 0
print(my_find('this is a book', 'this', start=1))# -> -1