1 class Solution:
 2     def numKLenSubstrNoRepeats(self, S: str, K: int) -> int:
 3         n = len(S)
 4         if n < K:
 5             return 0
 6         cnt = 0
 7         dic = {}
 8         i = 0
 9         j = 0
10         while i <= n - K:
11             nexti = i
12             while j < i + K:
13                 if S[j] not in dic:
14                     dic[S[j]] = j
15                     j += 1
16                 else:
17                     nexti = dic[S[j]] + 1
18                     break
19             if j == i + K:
20                 cnt += 1
21                 dic.pop(S[i])
22                 i += 1
23             else:
24                 for k in range(i,nexti):
25                     dic.pop(S[k])
26                 i = nexti
27         return cnt

思路:滑动窗口,在字典中保存窗口内出现过的字符,如果在窗口内遇到重复的字符,则向右移动,并将移出窗口外的字符从字典中移除。

posted on 2019-06-29 23:56  Sempron2800+  阅读(288)  评论(0编辑  收藏  举报