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

题目描述

159. 至多包含两个不同字符的最长子串

image-20250418172934942

思路分析

滑动窗口问题

参考代码

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

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

		freq[s[right]]++

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

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

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

➡️ 点击查看 Java 题解

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