LeetCode Solutions

424. Longest Repeating Character Replacement

Time: $O(n)$

Space: $O(128) = O(1)$

			

class Solution {
 public:
  int characterReplacement(string s, int k) {
    int ans = 0;
    int maxCount = 0;
    vector<int> count(128);

    for (int l = 0, r = 0; r < s.length(); ++r) {
      maxCount = max(maxCount, ++count[s[r]]);
      while (maxCount + k < r - l + 1)
        --count[s[l++]];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
			

class Solution {
  public int characterReplacement(String s, int k) {
    int ans = 0;
    int maxCount = 0;
    int[] count = new int[128];

    for (int l = 0, r = 0; r < s.length(); ++r) {
      maxCount = Math.max(maxCount, ++count[s.charAt(r)]);
      while (maxCount + k < r - l + 1)
        --count[s.charAt(l++)];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
			

class Solution:
  def characterReplacement(self, s: str, k: int) -> int:
    ans = 0
    maxCount = 0
    count = Counter()

    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      maxCount = max(maxCount, count[c])
      while maxCount + k < r - l + 1:
        count[s[l]] -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans