Python O(n) solution 79ms beats 98%


  • 0
    2
    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            if len(s) == 0: return 0
            lo, max_c = 0, 0
            dic = {}
            for i, c in enumerate(s):
                if c in dic and dic[c]>=lo:
                    index = dic[c]
                    max_c = max(i-lo, max_c)
                    lo = index+1
                    if lo > len(s)-max_c: break
                dic[c] = i
            return max(len(s)-lo, max_c)
    

Log in to reply
 

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