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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。