Python solution with comments.

  • 27
    def lengthOfLongestSubstring(self, s):
        dic, res, start, = {}, 0, 0
        for i, ch in enumerate(s):
            if ch in dic:
                # update the res
                res = max(res, i-start)
                # here should be careful, like "abba"
                start = max(start, dic[ch]+1)
            dic[ch] = i
        # return should consider the last 
        # non-repeated substring
        return max(res, len(s)-start)

  • 0

    very good.
    Why nobady is here!
    If we not use enumerate, it will be faster although less readable

  • 0

    I learn more.

  • 0

    Thank you so much for your code!
    Could you please explain the use of the ',' behind the first line 'start'? Is there some particular use of it or just type mistake

  • 0

    hi, it's a very interesting program,however could you please give me a tip on how and why it works?
    it makes me confused for a while .

Log in to reply

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