Find K-Length Substrings With No Repeated Characters in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string S, we have to find the number of substrings of length K where no characters are repeated. So if S = “heyfriendshowareyou” and K is 5, then output will be 15, as the strings are [heyfr, eyfri, yfrie, frien, riend, iends, endsh, ndsho, dshow, showa, howar, oware, warey, areyo, reyou]

To solve this, we will follow these steps −

• create one empty map m, and left := 0 and right := -1 and ans := 0
• while right < length of string – 1
• if right – left + 1 = k, then
• increase ans by 1
• decrease m[str[left]] by 1
• increase left by 1
• continue to next iteration
• if str[right + 1] is not in m, then
• set m[str[right + 1]] := 1
• increase right by 1
• else if m[str[right + 1]] is 0, then
• increase m[str[right + 1]] by 1
• increase right by 1
• else
• decrease m[str[left]] by 1
• left := left + 1
• if right – left + 1 = k, then increase ans by 1
• return ans

Example

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def numKLenSubstrNoRepeats(self, S, K):
m = {}
left = 0
right = -1
ans = 0
while right<len(S)-1:
if right - left + 1 == K:
ans+=1
m[S[left]]-=1
left+=1
continue
if S[right+1] not in m :
m[S[right+1]]=1
right+=1
elif not m[S[right+1]]:
m[S[right+1]]+=1
right+=1
else:
m[S[left]]-=1
left+=1
if right - left + 1 == K:
ans+=1
return ans
ob1 = Solution()
print(ob1.numKLenSubstrNoRepeats("heyfriendshowareyou", 5))

Input

"heyfriendshowareyou"
5

Output

"AIIOC"
Published on 27-Feb-2020 15:44:57