Accepted Python Answer in LeetCode
I've solved this using the power of lists in Python
The code below is well commented, however, I will explain the key point behind it.
By looping and adding unseen chars in the temporary list until the point where we catch an already found char, then update the max length if it is less than the new length of the temporary list.
The logic after this is for sure to clear up the temporary list, but here is the point, we have to do so if and only if the currently found char is the same as the previously added one in our temp list.
And if that is not the case and if the repeating char is found in a different index, we need to remove the elements from the temp list until the index of the found char. So that, we don't remove already added characters that would be possible to form the largest substring of the original string.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# temprary list to memorize chars
temp_list = []
# max length to track the length of the unique chars
max_len = 0
# loop for each char in s
for c in s:
if c in temp_list:
# if the current length of the list is greater than the previous one, then update
if len(temp_list) > max_len:
max_len = len(temp_list)
# if current character is the last added one, then reset
if c == temp_list[-1]:
temp_list = []
else: # in case where the current char found in differnet index, then, remove all elements up to it
temp_list = temp_list[temp_list.index(c)+1:]
# after process, add the new char
temp_list.append(c)
else: # it is a new char, then add it to the list
temp_list.append(c)
# in case we loop but we don't find repeating characters, then max_len would be zero, so that consider returning len(temp_list)
return max(max_len, len(temp_list))
Now, to address the test case that you experienced and if you try to print out the temp_list after each time we add a new char in the code above, you will get the following:
['d']
['d', 'v']
['v', 'd']
['v', 'd', 'f']
so that, it is clear that the longest substring is "vdf" and its length is 3
Please let me know if you don't understand any point clearly? Thanks!