Expert · String algorithms · 252 of 264
Longest stretch without repeats
Find the length of the longest run of consecutive characters with no character repeated. Use a sliding window (texts up to 9000 characters).
Input: one line. Output: the length.
Examples
Input
abcabcbb
Output
3
Input
bbbbb
Output
1
Input
pwwkew
Output
3
One more test checks other inputs when you press Check.
Stuck? The idea behind string algorithms
Finding patterns in text: compare a window of the text with the pattern as it slides along, or use what has already matched to skip ahead.
str.find(pattern, start) gives the next position, or -1 when there is none.
text, pat = "abababa", "aba"
i = text.find(pat)
while i != -1:
print(i)
i = text.find(pat, i + 1)Watch for: Matches can overlap ("aba" twice in "ababa"): move on by one, not by the pattern's length.