两个字符串,s1 包含 s2,包含多次,返回每一个匹配到的索引---python

#两个字符串,s1 包含 s2,包含多次,返回每一个匹配到的索引
def findSubIndex(str1,subStr):
    str_len = len(str1)
    sub_len = len(subStr)
    index_list = []
    for i in range(str_len):
        for k in range(sub_len):
            if str1[i+k] != subStr[k]:
                break
            if k >= sub_len-1:
                index_list.append(i)
    print(index_list)

def solution2(str1,subStr):
    str_len = len(str1)
    sub_len = len(subStr)
    index_list = []
    if str_len < sub_len:
        return -1
    k = 0
    for i in range(str_len):
        if str1[i] == subStr[k]:
            k += 1
        else:
            k = 0
        if k == sub_len:
            index_list.append(i-k+1)
            k = 0
    print(index_list)



if __name__ == "__main__":
    string = 'i find an interesting thing,do you wnant to know .find it. It is a secret. You will like it.'
    sub = 'find'
    findSubIndex(string,sub)
    solution2(string,sub)

 

posted @ 2020-03-11 22:18  图图图图胡图图  阅读(505)  评论(0编辑  收藏  举报