Search code examples
pythonsubstring

Trouble trying to find length of longest substring


I wrote the following code. It should return to me the length of the longest subscript in a string without a repeat in letters.

def lengthOfLongestSubstring(s):
    lst = []
    y = 0
    final = 0
    count = len(s)      
    while len(s) > 0:
        s = s[y:]            
        for i in range(len(s)):
            if s[i] in lst:
                y += 1
                count = len(lst)
                lst =[]
                break
            else:
                lst.append(s[i])

        if count > final:
            final=count 
    return(final)

when entering the string "tmmzuxt" i expect to get an output of 5 (length of "mzuxt") but instead get 4. I have debugged to figure out the problem seems to be that my function skips over the second 'm' when indexing but I can't figure out why. Any suggestions?

Realized I somehow missed a line. Hope this makes more sense.


Solution

  • The main problem with your code is that you incremented y, even though it should only ever remove the first character. There is no need for a variable y. Try this:

    def lengthOfLongestSubstring(s):
        final = 0
        while len(s) > 0:
            count = len(s)
            lst = []
            for i in range(len(s)):
                if s[i] in lst:
                    count = i - 1
                    break
                lst.append(s[i])
            if count > final:
                final = count
            s = s[1:]
        return final
    
    print(lengthOfLongestSubstring("tmmzuxt"))