5-line Python, sliding window, easy to understand


  • 0
    K

    Use a sliding window, all characters inside this window are unique. Window border is [left + 1, right] and window size is right - left.

    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        last_index, result, left = {}, 0, -1
        for right, char in enumerate(s):
            left = max(left, last_index.get(char, -1))
            last_index[char], result = right, max(result, right - left)
        return result
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.