Advertisement
aero2146

Longest Substring With At Most K Distinct Chars

Apr 10th, 2020
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. from collections import defaultdict
  2. class Solution:
  3.     def lengthOfLongestSubstringKDistinct(self, s: 'str', k: 'int') -> 'int':
  4.         n = len(s)
  5.         if k == 0 or n == 0:
  6.             return 0
  7.        
  8.         # sliding window left and right pointers
  9.         left, right = 0, 0
  10.         # hashmap character -> its rightmost position
  11.         # in the sliding window
  12.         hashmap = defaultdict()
  13.  
  14.         max_len = 1
  15.        
  16.         while right < n:
  17.             # add new character and move right pointer
  18.             hashmap[s[right]] = right
  19.             right += 1
  20.  
  21.             # slidewindow contains 3 characters
  22.             if len(hashmap) == k + 1:
  23.                 # delete the leftmost character
  24.                 del_idx = min(hashmap.values())
  25.                 del hashmap[s[del_idx]]
  26.                 # move left pointer of the slidewindow
  27.                 left = del_idx + 1
  28.  
  29.             max_len = max(max_len, right - left)
  30.  
  31.         return max_len
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement