题解 | 小红的01子序列构造(easy)
小红的01子序列构造(easy)
https://www.nowcoder.com/practice/ee0b6c6baa2642c182df8b4390126f9a
from collections import defaultdict # 双指针 滑动窗口 哈希 n, k = map(int, input().split()) s = input() left = 0 cur_01 = 0 # 代表当前01子串个数 cache = defaultdict(int) for i, c in enumerate(s): if c == '1': cache[1] += 1 cur_01 += cache[0] # 此前有多少0,就增加多少01子串 if cur_01 == k: print(left + 1, i + 1) break while cur_01 > k: # 加上当前元素后,01子串个数超出要求,移动左指针,减小窗口 if s[left] == '0': cur_01 -= cache[1] # 0脱离窗口,此后有多少1,就减少多少01子串 cache[0] -= 1 # 更新cache else: cache[1] -= 1 # 左1离开窗口,不影响01子串个数 left += 1 if cur_01 == k: # 左指针移动结束,检查是否刚好达到目标 print(left + 1, i + 1) break else: cache[0] += 1 if cur_01 != k: # 没找到,输出-1 print(-1)
使用滑动窗口做法,right指针就是for循环中的i,增加right,直到窗口中01子串超出个数就移动left。如果窗口中个数符合要求,则打印此时的left,right,退出循环。