Use of enumerate and dict.get


  • 0
    D
    class Solution:
        def lengthOfLongestSubstring(self, s):
            '''length of longest substring without repetition'''
            max_length, start, used_chars = 0, 0, {}
            for idx, char in enumerate(s, 1):
                if used_chars.get(char, -1) >= start:
                    start = usedChars[char]
                used_chars[char] = idx
                max_length = max(max_length, idx - start)
            return max_length
    

    Solution in O(n)

    • dict.get takes a default argument, so no need to check if char in usedChars.
    • enumerate takes also a second argument to specify starting number, it skips at most 2 additions per cycle.

Log in to reply
 

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