Leetcode 3 : Longest Substring without Repeating Characters
This is python program for finding len of longest substring in given argument with no duplicates
Leetcode 3
Will share optimized version later
Longest substring without repeating characters
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# will post best version on https://www.computerscienceai.com
#print = lambda *args , **kwargs : None
l = {}; ls = 0;
#s = "123412345!@#" ;
li = 0 # this is last changed index
for i , ch in enumerate(s):
if ch in l:
#print(f"{ch} in l")
# longest substring is
# earlier attempt
new_len = i - 1 - li if ls != 0 else i
if new_len > ls :
#print(f"len is greater , new length { i - 1 - li }")
ls = new_len
#print("Before clearning : " , l)
# here we can drop keys which are earlier than i but doing so will hur performance so we will join it later
li = l.pop(ch ) # none is danger
l[ch] = i
#print("Current char is added")
#print("After clearing : " , l)
else:
l[ch] = i ;
#print(l)
#print( l ) ; print ( li )
# check once if we have longest substring now
l = { ch : 0 for ch , v in l.items() if v >= li }
if ls < len(l):
ls = len( l )
# that is it boy
return ls
Comments