81. Longest stretch without a repeat
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
text = "abcdbef"5Example 2
text = "aaaa"1Example 3
text = ""0Constraints
texthas 0 to 500 characters, of any kind.
Submit also runs 10 more tests you can't see.
- Keep a window from
leftto the current indexiwith no repeats, and a dictionarylastof the index where each character was last seen. - When the character at
iwas last seen inside the window, moveleftto just after that index. Its length is theni - left + 1. - Use
left = max(left, last[ch] + 1): a copy seen before the window started mustn't dragleftback to the left."abba"has the answer 2, not 3.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.