classSolution(object): deflengthOfLongestSubstring(self, s): visited = set() left = right = 0 cnt = 0 n = len(s) while right < n: if s[right] notin visited: visited.add(s[right]) right += 1 cnt = max(cnt, right-left) else: visited.remove(s[left]) left += 1 return cnt
classSolution(object): deffindAnagrams(self, s, p): m, n = len(s), len(p)
char_dic = collections.defaultdict(int) cnt = 0
# Init p : count char in p for ch in p: char_dic[ch] += 1 if char_dic[ch] == 1: cnt += 1
# Init sliding window for ch in s[:n]: if ch notin char_dic: continue
char_dic[ch] -= 1 if char_dic[ch] == 0: cnt -= 1
res = [] if cnt == 0: res.append(0)
# move the Fixed size sliding window for i in xrange(m-n): if s[i] in char_dic: char_dic[s[i]] += 1 if char_dic[s[i]] == 1: cnt += 1 if s[i+n] in char_dic: char_dic[s[i+n]] -= 1 if char_dic[s[i+n]] == 0: cnt -= 1 if cnt == 0: res.append(i+1)
return res
Flip 0 to 1
Given a 0-1 array, you can flip at most k ‘0’s to ‘1’s.Please find the longest subarray that consists of all ‘1’s.
Solution : Find a slinding window that contains at most k zeros.
When to move the right border: when the counter of zeros <=k
When to move the left border: when the counter of zeros >k
Clarify the information contains in the sliding window