A Python solution


  • 0
    H
    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            n = len(s)
            if n == 0:
                return 0
            
            buff = set()
            max_len = 0
            # the_slice = [0,  0] # record the max-len substring s[the_slice[0]:the_slice[1]] if needed
            cur_len = 0 # length of current substring
            
            i = j = 0
            while i < n:
                # slide the right index j until a repeating char.
                while j < n and not (s[j] in buff):
                    buff.add(s[j])
                    j += 1
                    cur_len += 1
                # update max_len
                if cur_len > max_len:
                    max_len = cur_len
                    # the_slice = [i, j]
                # slide the left index i (update buff first) 
                buff.remove(s[i])
                i += 1
                cur_len -= 1
                
            return max_len
    

Log in to reply
 

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