标明来源,题目及解题思路均来自:https://leetcode.cn/problems/longest-substring-without-repeating-characters/
题目:无重复字符的最长字串
给定一个字符串s,请你找出其中不含有重复字符的最长字串的长度。
python
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic, res, i = {}, 0, -1
for j in range(len(s)):
if s[j] in dic:
i = max(dic[s[j]], i) # 更新左指针 i
dic[s[j]] = j # 哈希表记录
res = max(res, j - i) # 更新结果
return res
这个题考的是滑动窗口,核心是用哈希表记录字符最新位置。
我还写了一个直白点的做法:
python
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# 用集合存储当前窗口的字符
window = set()
left = 0 # 窗口左边界
max_len = 0 # 记录最长长度
for right in range(len(s)):
# 如果当前字符已在窗口中,不断移动左边界直到移除重复字符
while s[right] in window:
window.remove(s[left])
left += 1
# 将当前字符加入窗口
window.add(s[right])
# 更新最长长度(当前窗口长度:right - left + 1)
max_len = max(max_len, right - left + 1)
return max_len
滑动窗口的知识点倒是没怎么为难我,所以我不写知识点。
好的,继续干下一篇。