O(n) 9 lines in Python - 29ms


  • 0
    X

    We just need to return the length of substring not the whole substring. So I use a list to store the substring when iterate given string, once I find the character which has already been in list_store, I'll get the location index in list_store and then restore list_store from location index+1. Repeat it till the end.

    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            list_store = []
            max_len = 0
            for i in s:
                if i in list_store:
                    list_store = list_store[list_store.index(i)+1:]
                list_store.append(i)
                max_len = max(max_len, len(list_store))
            return max_len
    

Log in to reply
 

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