Skip to content

Longest substring without repeat

Given a string s, find the length of the longest substring without repeating characters.

Example 1

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Solution

def max_sub_str(string: str) -> int:
    maximum_substr = ""
    answer = 0
    window = ""
    for i, s in enumerate(string):
        if s not in window:
            window += s
        else:
            while s in window:
                window = window[1:]
            window += s

        if len(window) > answer:
            answer = max(len(window), answer)
            maximum_substr = window

    print(f"Max substring: {maximum_substr}")
    return answer

max_sub_str("abcabcbb")
Max substring: abc





3