LeetCode: Longest Substring Without Repeating Characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def lengthOfLongestSubstring(s: str) -> int:
    """
    Calculates the length of the longest substring without repeating characters.

    Args:
        s (str): The input string.

    Returns:
        int: The length of the longest substring.

    Examples:
        >>> lengthOfLongestSubstring("abcabcbb")
        3
        >>> lengthOfLongestSubstring("bbbbb")
        1
        >>> lengthOfLongestSubstring("pwwkew")
        3
    """
    max_index = len(s) - 1
    start, end = 0, 0
    longest, substring = set(), set()
    while start <= max_index and end <= max_index:
        character = s[end]
        if character in substring:
            substring = set()
            start += 1
            end = start
        else:
            substring.add(character)
            end += 1
        longest = substring if len(substring) > len(longest) else longest
    return len(longest)
0%