LeetCode 3. 无重复字符的最长子串

题目描述

3. 无重复字符的最长子串

image-20230306130630185

思路分析

滑动窗口问题

image-20250506022932434

参考代码

image-20250508211812923

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func lengthOfLongestSubstring(s string) int {
	left, right := 0, 0
	dict := make(map[byte]bool)
	res := 0
	for right < len(s) {
		c := s[right]
		for dict[c] {
			delete(dict, s[left])
			left++
		}
		res = max(res, right-left+1)

		dict[c] = true
		right++
	}
	return res
}
  • 时间复杂度:O(n),每个字符最多进出窗口一次。
  • 空间复杂度:O(k),其中 k 是字符集大小。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func lengthOfLongestSubstring(s string) int {
	left, right := 0, 0
	dict := make(map[byte]int)
	res := 0
	for right < len(s) {
		c := s[right]
		if index, ok := dict[c]; ok {
			left = max(left, index+1)
		}
		res = max(res, right-left+1)
		dict[c] = right
		right++
	}
	return res
}

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/11034463
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!