Advertisement
nathanwailes

LeetCode 424 - Longest Repeating Character Replacement - Rewritten NeetCode solution

Oct 14th, 2023
1,270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. class Solution:
  2.     def characterReplacement(self, s: str, k: int) -> int:
  3.         chars_in_the_current_window = defaultdict(int)
  4.         longest_substring = 0
  5.  
  6.         l = 0
  7.         for r in range(len(s)):
  8.             chars_in_the_current_window[s[r]] += 1
  9.  
  10.             while _chars_other_than_the_most_common(l, r, chars_in_the_current_window) > k:
  11.                 chars_in_the_current_window[s[l]] -= 1
  12.                 l += 1
  13.            
  14.             longest_substring = max(longest_substring, _the_window_size(l, r))
  15.         return longest_substring
  16.  
  17. def _chars_other_than_the_most_common(l, r, chars_in_the_current_window):
  18.     return _the_window_size(l, r) - _the_number_of_occurrences_of_the_most_common_character(chars_in_the_current_window)
  19.  
  20. def _the_window_size(l, r):
  21.     return r - l + 1
  22.  
  23. def _the_number_of_occurrences_of_the_most_common_character(chars_in_the_current_window):
  24.     return max(chars_in_the_current_window.values())
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement