Simple O(n) Python Solution (78-95ms)


  • 0
    B
        def lengthOfLongestSubstring(self, s):
            currentLongest = s[0:1]
            longestStr = ""
            for c in s[1:]:
                if c not in currentLongest:
                    currentLongest += c
                else:
                    if len(longestStr) < len(currentLongest): #if current string is longer than current longest string
                        longestStr = currentLongest
                    if c in currentLongest:
                        currentLongest = currentLongest[currentLongest.find(c)+1:]+c
                    elif c != currentLongest[-1:]:
                        currentLongest = currentLongest[-1:]+c
                    else:
                        currentLongest = c
            if len(currentLongest) > len(longestStr): #final check with last substring
                return len(currentLongest)
            return len(longestStr)```

Log in to reply
 

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