17-line Python solution in O(n) time


  • 0
    L
    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            
            l, cnt, max_v, unrepeat = len(s), 0, 0, []
            
            for i in range(l):
                if s[i] in unrepeat:
                    x = unrepeat.index(s[i])
                    unrepeat = unrepeat[x+1:]
                    unrepeat.append(s[i])
                    cnt = len(unrepeat)
                else:
                    unrepeat.append(s[i])
                    cnt += 1
                    max_v = max(max_v, cnt)
            
            return max_v
    

Log in to reply
 

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