LeetCode 340. 至多包含 K 个不同字符的最长子串

题目描述

340. 至多包含 K 个不同字符的最长子串

image-20250418173337399

思路分析

这道题是经典的滑动窗口问题,要求我们找出包含至多 k 个不同字符的最长子串。

image-20250509231057912

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func lengthOfLongestSubstringKDistinct(s string, k int) int {
	var res, left int
	charCount := make(map[byte]int)

	for right := 0; right < len(s); right++ {
		charCount[s[right]]++

		// 如果窗口中不同字符的个数超过了 k
		for len(charCount) > k {
			charCount[s[left]]--
			if charCount[s[left]] == 0 {
				delete(charCount, s[left])
			}
			left++
		}

		res = max(res, right-left+1)
	}

	return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func lengthOfLongestSubstringKDistinct(s string, k int) int {
	left, res := 0, 0
	freq := make(map[byte]int)

	for right := 0; right < len(s); right++ {
		freq[s[right]]++

		for len(freq) > k {
			freq[s[left]]--
			if freq[s[left]] == 0 {
				delete(freq, s[left])
			}
			left++
		}

		res = max(res, right-left+1)
	}

	return res
}
  • 时间复杂度:O (n)
  • 空间复杂度:O (k)

➡️ 点击查看 Java 题解

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