Le migliori 150 intervisteFacile

Sostituzione dei caratteri che si ripetono più a lungo

Guida dettagliata e implementazione Python per il problema della "Sostituzione dei caratteri con ripetizione più lunga".

Dichiarazione del problema

Facile

Ti viene data una stringa s e un numero intero k. Puoi scegliere qualsiasi carattere della stringa e cambiarlo in qualsiasi altra lettera inglese maiuscola. Puoi eseguire questa operazione al massimo k volte.

Restituisce la lunghezza della sottostringa più lunga contenente la stessa lettera che puoi ottenere dopo aver eseguito le operazioni precedenti.

Scrivi una funzione characterReplacement(s: str, k: int) -> int.

Vincoli
  • 1 <= len(s) <= 10^5
  • s consists of only uppercase English letters
  • 0 <= k <= len(s)

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche della finestra scorrevole come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.