Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading