Elegant Python solution O(n)!


  • 0
    A
    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            d={}
            if len(s)<=1:
                return len(s)
            aux,res,count,i,n=0,1,0,0,len(s)
            while i<n:
                if s[i] not in d:
                    d[s[i]]=i
                    i+=1
                    count+=1
                else:
                    i=d[s[i]]+1
                    d.clear()
                    res=max(count,res)
                    count=0
            res=max(count,res)
            return res
    

Log in to reply
 

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