imashutosh51

Longest Substring with At Least K Repeating Characters

Oct 30th, 2022 (edited)
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. from collections import Counter
  2.  
  3. '''
  4. suppose we have input as s="aaabbccddeeeddd" and k=3 here Counter(s)={a=3,b=2,c=2,d=5,e=3} so one thing is for sure that b and c can't come in the our Longest Substring so better split on b and c.
  5. so now probable answers=[aaa,ddeeeddd] so we will check again on them here aaa is a good answer and then again ddeeeddd is also a good answer so it will be the answer.
  6.  
  7. Approach: We will break on the chars whose count is less than k because those chars with freq less than k can never be part of your answer so do the split on them now again, those splits are your probable answer and again check on them.
  8. '''
  9. from collections import Counter
  10. def fun(s, k):
  11.     if len(s) < k:
  12.         return 0
  13.    
  14.     freq = Counter(s)
  15.     ans = 0
  16.    
  17.     for ch in freq:
  18.         if freq[ch] < k:
  19.             probable_answers = list(s.split(ch))
  20.  
  21.             for p in probable_answers:
  22.                 ans = max(ans, fun(p, k))
  23.             return ans   #return after split because this bad char can never be considered so no point of splitting on some other bad char because that will club these bad chars with anoter characters
  24.    
  25.     return len(s)   #this probable string s is valid
  26.  
  27. class Solution:
  28.     def longestSubstring(self, s: str, k: int) -> int:
  29.         if len(s) < k:
  30.             return 0
  31.         return fun(s,k)
Advertisement
Add Comment
Please, Sign In to add comment