100 XP

81. Longest stretch without a repeat

Advanced sliding window strings

Write a function longest_unique(text) that takes a string and returns the length of the longest stretch of it (characters next to each other) in which no character appears more than once.

  • The stretch must be in one piece: in "abcdbef" the answer is 5, for "cdbef".
  • Every character counts, spaces and punctuation included, and capitals are different from lower case.
  • An empty string has no stretch, so the answer is 0.

Checking every stretch is slow. A window that slides along the string can do it in one pass: it grows on the right, and when the new character is already inside it, its left edge jumps just past the earlier copy.

Example 1

Inputtext = "abcdbef"
Output5
Explanation"cdbef": the window restarts after the b.

Example 2

Inputtext = "aaaa"
Output1
ExplanationAny two characters in a row repeat.

Example 3

Inputtext = ""
Output0
ExplanationNothing to look at.

Constraints

  • text has 0 to 500 characters, of any kind.

Submit also runs 10 more tests you can't see.

Code
def longest_unique(text):
    """Find the longest stretch with no repeated character.

    text: str; may be empty
    Returns: int, the length of the longest run of
        characters in which none appears twice
    """
    # Write your code here
    pass