subject : Please find the longest substring in the string that does not contain duplicate characters , Calculate the length of the longest substring .
for example :
“abcabcbb” “abc” The length is 3
“bbbbb” “b” The length is 1
“dvdf” “vdf” The length is 3
Analytic process , See also leetcode: Power button
Dynamic programming + Hashtable (python Dictionary ), It can also be understood as two pointers .
Code :
class Solution:
def func(self , s):
if len(s) == 0:
return 0
elif len(s) == 1:
return 1
save = dict() # Save the maximum position of each letter , Immediate replacement with duplicate
res = 0
j = 0
for i in range(len(s)):
if i == 0:
res = 1
else:
if s[i] not in save.keys():
res += 1
else:
j = save[s[i]]
res = max(res , (i - 1) - j) # Dynamic equation
save[s[i]] = i
print('i = {} , j = {} , save = {}'.format(i , j , save))
return res
s = Solution()
a = 'abcabcbb'
print(s.func(a))
Output :