Skip to main content

Longest Substring Without Repeating Characters

Question

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

Example 1
Input: "abcabcbb"

Output: 3 (The longest substring without repeating characters is "abc")

Solution

all//Longest Substring Without Repeating Characters.py


def longestSubstring(s):
st = 0
maxLen = 0
start = 0
usedChar = {}

for i in range(len(s)):
if s[i] in usedChar and st <= usedChar[s[i]]:
st = usedChar[s[i]]
else:
maxLen = max(maxLen, i - st + 1)

usedChar[s[i]] = i

return maxLen

print(longestSubstring("abccdefgh"))