Le migliori 150 intervisteMedio

Modifica distanza

Guida dettagliata e implementazione Python per il problema "Modifica distanza".

Dichiarazione del problema

Medio

Date due stringhe word1 e word2, restituisce il numero minimo di operazioni richieste per convertire word1 in word2.

Su una parola sono consentite le seguenti tre operazioni:

1. Inserisci un carattere

2. Elimina un carattere

3. Sostituisci un carattere

Scrivi una funzione minDistance(word1: str, word2: str) -> int.

Vincoli
  • 0 <= len(word1), len(word2) <= 500
  • word1 and word2 consist of lowercase English letters

Esempi

Example 1
Input
word1 = "horse", word2 = "ros"
Output
3
Explanation

horse -> rorse (replace 'h' with 'r') -> rose (remove 'r') -> ros (remove 'e').

Example 2
Input
word1 = "intention", word2 = "execution"
Output
5
Explanation

intention -> extention -> exention -> exection -> execution. Total 5 operations.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per DP 2D 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.