-1

I am trying to write a program that returns the length of longest substring within a string. This is my code:

def lengthOfLongestSubstring():
dict = {}
s = 'dvdf'
max_substr_length = 0
max_substr = ''
if len(s) < 1:
    return 0
else:
    for letter in s:
        print('String value: ', s)
        if letter not in max_substr:
            max_substr = max_substr + letter
            max_substr_length = len(max_substr)
            dict[max_substr] = dict.get(max_substr, max_substr_length)
            print(letter, max_substr, max_substr_length, dict)
        elif letter in max_substr:
            dict[max_substr] = dict.get(max_substr, max_substr_length)
            s = s[s.index(letter)+1:]
            max_substr = ''
            max_substr_length = 0
            print(s, letter, max_substr, max_substr_length, dict)
    print(dict)
    print(max(dict.values(), default=0))

For the input string s = 'dvdf' I am getting rid of the first instance of the letter that gets repeated in the input string s, in line 18 of my code s = s[s.index(letter)+1:]. So when the second 'd' is encountered, s should get updated to s = 'vdf' Unfortunately, the for loop doesn't start iterating from the 0th index of this new s. Is there a way that doesn't involve iterating over integer indexes to get the for loop to begin iterating from the beginning when the string is updated?

Bittu
  • 79
  • 1
  • 8
  • what do you mean the longest substring? do you mean the longest string where the same letter doesnt occur more than once? – Chris Doyle Mar 04 '20 at 23:26
  • Yes. longest substring with non-repeating characters. Eg: ip: 'abcacbb' , op: 3 ip : 'dvdf', op:3 – Bittu Mar 04 '20 at 23:29
  • like this? please do at least try to use the search function :/ https://stackoverflow.com/questions/48343033/longest-substring-with-non-repeating-character – Aiyion.Prime Mar 04 '20 at 23:30
  • I know solutions exist, I am just trying something different. – Bittu Mar 04 '20 at 23:31

1 Answers1

0

Well, no not this way. Python iterates whatever was s in the beginning of the loop.

You should try a different approach like using a cellar storage.

Push every letter to it in the correct order,

   loop untils its empty,

   pop a value,

   do whatever you want with it,

   push a value to it, if necessary.

in the end you should have a working example.

Aiyion.Prime
  • 973
  • 9
  • 20
  • Is this like a FCFS queue that involves popping off characters (substrings?) upto and including the index of the first instance of repeating character and then reiterating? – Bittu Mar 04 '20 at 23:42
  • An FCFS (or FIFO) is not what I tried to describe, but this: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) – Aiyion.Prime Mar 04 '20 at 23:56