查找最长子字符串(Python版本)

def find_longest_substr(source_str):
    substr_lenght = 0
    substr_start = 0
    left = 0
    right = 1
    char_position = {}
    char_position[source_str[0]] = 0
    while (right < len(source_str)):
        cur_char = source_str[right]
        last_pos = char_position.get(cur_char, None)
        if last_pos is not None and last_pos >= left: #found
            cur_length = right - last_pos
            if cur_length > substr_lenght:
                substr_start = left
                substr_lenght = cur_length
            left = last_pos + 1

        char_position[cur_char] = right
        right += 1

    return source_str[substr_start: substr_start + substr_lenght + 1]

if __name__ == "__main__":
    print(find_longest_substr('abcdabcdefabcabdefg12345p67890acccghdkjzabc'))


版权声明:本文为deyili原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。