hash表记录
出现过的数字最后出现的位置
dp的子问题是 dp[i] = 以a[i]为结尾的最长子串的长度
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s)
if length <= 1:
return length
hashdict = {}#记录出现过的每一个字母出现的最后的位置
dp = [1]
for i in range(length):
this = s[i]
if i == 0:
hashdict[s[i]] = 0
elif this not in hashdict:
hashdict[this] = i
dp.append(dp[-1] + 1)
elif this in hashdict:
if dp[-1] >= i - hashdict[this]:#说明此时以a[i-1]为结尾的最长子串中包含a[i]
dp.append(i - hashdict[this])
hashdict[this] = i
else:
hashdict[this] = i
dp.append(dp[-1] + 1)
return max(dp)
07.12更新
class Solution:
def __init__(self):
self.maxa = 0
self.res = {}
self.start = 0
def lengthOfLongestSubstring(self, s: str) -> int:
if s == '':
return 0
self.maxa = 1
self.res = {s[0]:0}
length = len(s)
for i in range(1,length):
self.func(s[i],i)
return self.maxa
def func(self,l,i):
if l in self.res and self.res[l] >= self.start:
self.maxa = max(i - self.res[l],self.maxa)#
self.start = self.res[l] + 1
else:
self.maxa = max(i + 1 - self.start,self.maxa)
self.res[l] = i