双指针
哈希表记录字符出现次数
Python用字典,设置默认值为0
import collections
dic = collections.defaultdict(lambda :0)
import collections
# dic = collections.defaultdict(lambda :0)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
hash = collections.defaultdict(lambda :0) # 设置默认值为0
res = 0
i = 0; j = 0 # j为右指针,i为左指针
while j < len(s):
hash[s[j]] += 1
while hash[s[j]] > 1:
# 当右指针指向的字符出现两次时,左指针向右移动直到把前面的重复字符删掉为止
hash[s[i]] -= 1
i += 1
res = max(res, j - i + 1)
j += 1
# print(hash)
return res