解析一: 字典保存之前的子串,如出现重复,则可以从重复的子串处位置进行原串的截取从而继续往下找
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
has_dict = {}
for i, c in enumerate(s):
if c in has_dict:
return max(self.lengthOfLongestSubstring(s[has_dict[c]+1::]), len(has_dict))
else:
has_dict[c] = i
return len(has_dict)
解析二:方法一中会频繁的对字符串进行截图操作,当字符串很长时,会带来较大的内存和耗时开销。参考第一种办法的实现,对已保存的字典进行弹出操作
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
has_dict = {}
result = 0
for i, c in enumerate(s):
if c in has_dict:
result = max(len(has_dict), result)
idx = has_dict[c]
for k in list(has_dict.keys()):
if has_dict[k] <= idx:
del has_dict[k]
has_dict[c] = i
return max(result, len(has_dict))