Python solution with comments.


  • 27
    C
    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

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


  • 0
    W

    Nice!
    I learn more.
    Thanks!


  • 0
    A

    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
    D

    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.