返回介绍

solution / 0400-0499 / 0424.Longest Repeating Character Replacement / README_EN

发布于 2024-06-17 01:04:00 字数 3461 浏览 0 评论 0 收藏 0

424. Longest Repeating Character Replacement

中文文档

Description

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return _the length of the longest substring containing the same letter you can get after performing the above operations_.

 

Example 1:

Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.

Example 2:

Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
There may exists other ways to achieve this answer too.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only uppercase English letters.
  • 0 <= k <= s.length

Solutions

Solution 1

class Solution:
  def characterReplacement(self, s: str, k: int) -> int:
    counter = [0] * 26
    i = j = maxCnt = 0
    while i < len(s):
      counter[ord(s[i]) - ord('A')] += 1
      maxCnt = max(maxCnt, counter[ord(s[i]) - ord('A')])
      if i - j + 1 > maxCnt + k:
        counter[ord(s[j]) - ord('A')] -= 1
        j += 1
      i += 1
    return i - j
class Solution {
  public int characterReplacement(String s, int k) {
    int[] counter = new int[26];
    int i = 0;
    int j = 0;
    for (int maxCnt = 0; i < s.length(); ++i) {
      char c = s.charAt(i);
      ++counter[c - 'A'];
      maxCnt = Math.max(maxCnt, counter[c - 'A']);
      if (i - j + 1 - maxCnt > k) {
        --counter[s.charAt(j) - 'A'];
        ++j;
      }
    }
    return i - j;
  }
}
class Solution {
public:
  int characterReplacement(string s, int k) {
    vector<int> counter(26);
    int i = 0, j = 0, maxCnt = 0;
    for (char& c : s) {
      ++counter[c - 'A'];
      maxCnt = max(maxCnt, counter[c - 'A']);
      if (i - j + 1 > maxCnt + k) {
        --counter[s[j] - 'A'];
        ++j;
      }
      ++i;
    }
    return i - j;
  }
};
func characterReplacement(s string, k int) int {
  counter := make([]int, 26)
  j, maxCnt := 0, 0
  for i := range s {
    c := s[i] - 'A'
    counter[c]++
    if maxCnt < counter[c] {
      maxCnt = counter[c]
    }
    if i-j+1 > maxCnt+k {
      counter[s[j]-'A']--
      j++
    }
  }
  return len(s) - j
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文