算法思路:
left is left pointer, i is right pointer 外循环为扩张,内循环为收缩。收缩条件为固定字符种数(必须固定或者少于k)或者(以及)固定字符频数。若字符种数不固定,要试1-26种字符,才能单调,详见L395
求最短串
Python代码:
1
2
3
4
5
6
7
8def two_pointers(self, nums):
for i in range(len(nums)):
<calculate condition such as char_to_count>
while <meets condition>:
res = min(res, i - left + 1) <求最短子列>
<anti-calculate condition such as char_to_count>
left += 1
return <result>
求最长串
Python代码:
1
2
3
4
5
6
7
8def two_pointers(self, nums):
for i in range(len(nums)):
<calculate condition such as char_to_count>
while <does not meet condition>:
<anti-calculate condition such as char_to_count>
left += 1
res = max(res, i - left + 1) <求最短子列>
return <result>
算法分析:
时间复杂度为O(n),空间复杂度O(1)。


