LC 速查

HOT 100索引 › B3 滑动窗口 Sliding Window

LC 3无重复字符的最长子串Longest Substring Without Repeating Characters 中等

求字符串中不含重复字符的最长连续子串的长度。

思路 哈希表记录每个字符上一次出现的位置,左端点直接跳到重复位置的下一位。时间 O(n)。

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last = {}  # 字符上次出现的下标
        ans = l = 0
        for r, c in enumerate(s):
            if c in last and last[c] >= l:
                l = last[c] + 1
            last[c] = r
            ans = max(ans, r - l + 1)
        return ans
← 上一题 接雨水找到字符串中所有字母异位词 下一题 →