Simple python code, O(n) running time

  • 3
    class Solution:
        # @return an integer
        def lengthOfLongestSubstring(self, s):
            charUsed = {}
            start = curMax = 0
            for n,char in enumerate(s):
                if char in charUsed and charUsed[char] >= start:
                    start = charUsed[char]+1
                    charUsed[char] = n
                    charUsed[char] = n
                    curMax = max(curMax, n-start+1)
            return curMax

    Go through the string from left to right, whenever there is a duplicate character, update the start point and current maximum length.


Log in to reply

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