2021-02-02 [day33] Python百日打卡學(xué)習(xí)自【夸可編程】

'''
實(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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容