《剑指offer》面试题15:字符串中的所有变位词

"""
题目: 输入字符串S1和S2,如何找出字符串S1的所有变位词在字符串S2中的歧视下标?
解答思路: 这个题就是“字符串中的变位词”的轻微变种,无非就是在判断出是变为词后,把它的位置记录下来就行了。
"""


def has_brother(s1, s2):
    s1_length = len(s1)
    max_k = len(s2) - s1_length + 1
    # location_list记录变位词的起始位置
    location_list = []
    for k in range(max_k):
        s1_copy_list = list(s1)
        p1 = k
        p2 = p1 + s1_length
        sub_string = s2[p1:p2]
        for s in sub_string:
            if s in s1_copy_list:
                s1_copy_list.remove(s)
        if len(s1_copy_list) == 0:
            location_list.append(p1)
    if len(location_list) > 0:
        print('find them, and their location is ', location_list)
    else:
        print('not find them !')


s1 = 'pots'
s2 = 'stopsssss'
s3 = 'sdsastop'
s4 = 'sdsstopsdd'
s5 = 'sdsdstwop'
has_brother(s1, s2)
has_brother(s1, s3)
has_brother(s1, s4)
has_brother(s1, s5)

你可能感兴趣的:(笔记,python,算法,面试)