150强访谈简单

最长重复字符替换

“最长重复字符替换”问题的详细指南和 Python 实现。

问题陈述

简单

您将获得一个字符串 s 和一个整数 k。您可以选择字符串中的任何字符并将其更改为任何其他大写英文字母。您最多可以执行此操作 k 次。

返回执行上述操作后得到的包含相同字母的最长子串的长度。

编写一个函数 characterReplacement(s: str, k: int) -> int

约束条件
  • 1 <= len(s) <= 10^5
  • s consists of only uppercase English letters
  • 0 <= k <= len(s)

示例

Example 1
Input
s = "ABAB", k = 2
Output
4
Explanation

Replace the two 'A's with 'B's or vice versa to get "BBBB" or "AAAA". The longest substring is 4.

Example 2
Input
s = "AABABBA", k = 1
Output
4
Explanation

Replace the 'B' at index 3 with 'A' to get "AAAAABA". The longest substring of same characters starting from index 0 is "AAAA" with length 4.

Need a Hint?
考虑使用滑动窗口特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。