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 = {} # Tracks character frequencies in the current window
  11.  
  12. for j in range(len(s)):
  13. # Expand window: add current character to frequency map
  14. counts[s[j]] = counts.get(s[j], 0) + 1
  15.  
  16. # Shrink window: while max char ASCII - min char ASCII > k, remove from left
  17. # ord() converts characters like 'a' to 97, 'z' to 122, etc.
  18. while max(ord(ch) for ch in counts) - min(ord(ch) for ch in counts) > k:
  19. counts[s[i]] -= 1
  20. if counts[s[i]] == 0:
  21. del counts[s[i]] # Remove key so it doesn't affect min/max
  22. i += 1
  23.  
  24. # Calculate current window size and update maximum length
  25. current_len = j - i + 1
  26. if current_len > max_len:
  27. max_len = current_len
  28.  
  29. return max_len
  30.  
  31. # Example:
  32. # sol = Solution()
  33. # print(sol.longestSubstring("azbca", 2)) # Returns 3 (substring "bca" or "abc")
  34.  
Success #stdin #stdout 0.07s 13976KB
stdin
Standard input is empty
stdout
Standard output is empty