Skip to main content Link Search Menu Expand Document (external link)

Longest Substring Without Repeating Characters (Difficulty: Medium)

class Solution:
    @staticmethod
    def delete_substr(substr, i):
        del_keys = []
        for key in substr:
            if substr[key] < i:
                del_keys += [key]
        for key in del_keys:
            substr.pop(key)
                
    def lengthOfLongestSubstring(self, s: str) -> int:
        substr = {}
        x = []  # x[i] = length of longest substr having s[i]
        for i in range(len(s)):
            c = s[i]
            if c in substr:
                self.delete_substr(substr, substr[c])
            substr[c] = i
            # print(substr)
            x += [len(substr)]
        
        if len(x) ==0:
            return 0
        
        return max(x)