K-Substring with K different characters(sliding window)
Description
Example
String: "abcabc"
K: 3
Answer: 3
substrings: ["abc", "bca", "cab"]String: "abacab"
K: 3
Answer: 2
substrings: ["bac", "cab"]Last updated
String: "abcabc"
K: 3
Answer: 3
substrings: ["abc", "bca", "cab"]String: "abacab"
K: 3
Answer: 2
substrings: ["bac", "cab"]Last updated
class Solution:
"""
@param stringIn: The original string.
@param K: The length of substrings.
@return: return the count of substring of length K and exactly K distinct characters.
"""
import collections
def KSubstring(self, stringIn, K):
# Write your code here
map = collections.defaultdict(int)
i=j=0
cnt = 0
res = set()
strLen = len(stringIn)
for i in range(strLen):
c = stringIn[i]
map[c] += 1
if map[c] == 1:
cnt += 1
if i >= K:
c = stringIn[i - K]
map[c] -= 1
if map[c] == 0:
cnt -= 1
if cnt == K:
res.add(stringIn[i - K + 1:i + 1])
return len(res)