滑动窗口求解最长无重复子串存在Bug,请求排查
问题排查与修复
核心Bug分析
- 最后返回值计算错误:循环结束后
j已等于字符串长度,当前窗口的实际长度是j - i,而非j - i - 1。以测试用例"au"为例,循环结束时j=2、i=0,j-i=2才是正确的窗口长度,你的代码计算2-0-1=1,直接导致结果错误。 - 重复字符的指针更新逻辑错误:遇到窗口内的重复字符时,
i应更新为d[s[j]] + 1(跳过重复字符的旧位置),而不是直接跳到j。比如处理"abca"时,若i直接跳到j,会错过中间有效的"bca"子串。 - 最大长度更新时机不全:代码仅在遇到重复字符时更新
m,但循环结束后最后一个窗口可能是最长的,需要确保最后一次计算的准确性。
修复后的代码
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) < 2: return len(s) max_len = 1 left = 0 char_index = {s[0]: 0} right = 1 while right < len(s): if s[right] in char_index and char_index[s[right]] >= left: max_len = max(max_len, right - left) left = char_index[s[right]] + 1 char_index[s[right]] = right right += 1 return max(max_len, right - left)
验证说明
- 针对"au":循环结束后
right=2、left=0,right-left=2,max(1,2)=2,符合预期结果。 - 针对"abba":当
right=3(字符'a')时,char_index['a']=0,此时left更新为0+1=1,最后计算right-left=3,最终返回3,符合正确逻辑。
内容的提问来源于stack exchange,提问作者peter todds
相关产品推荐
相关产品推荐

