LeetCode 159. 至多包含两个不同字符的最长子串
题目描述
思路分析
滑动窗口问题
参考代码
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)
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用