3. Longest Substring Without Repeating Characters

Medium

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

😇 Solution

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        l = len(s)
        s_set = set()
        ans,i,j = 0,0,0
        
        while(i < l and j < l):
            if(s[j] not in s_set):
                s_set.add(s[j])
                j += 1
                ans = max(ans,j-i)
            else:
                s_set.remove(s[i])
                i += 1
        return ans

Last updated

Was this helpful?