fork download
  1. class Solution(object):
  2. def longestSubstring(self, s, k):
  3. """
  4. :type s: str
  5. :type k: int
  6. :rtype: int (returns the length of the longest substring)
  7. """
  8. i = 0
  9. max_len = 0
  10. counts = {}
  11.  
  12. for j in range(len(s)):
  13.  
  14. counts[s[j]] = counts.get(s[j], 0) + 1
  15.  
  16.  
  17. while max(ord(ch) for ch in counts) - min(ord(ch) for ch in counts) > k:
  18. counts[s[i]] -= 1
  19. if counts[s[i]] == 0:
  20. del counts[s[i]] # Remove key so it doesn't affect min/max
  21. i += 1
  22.  
  23.  
  24. current_len = j - i + 1
  25. if current_len > max_len:
  26. max_len = current_len
  27.  
  28. return max_len
  29.  
Success #stdin #stdout 0.08s 14020KB
stdin
Standard input is empty
stdout
Standard output is empty