Le migliori 150 intervisteMedio

Sottosequenza comune più lunga

Guida dettagliata e implementazione Python per il problema della "sottosequenza comune più lunga".

Dichiarazione del problema

Medio

Date due stringhe text1 e text2, restituiscono la lunghezza della loro sottosequenza comune più lunga. Se non esiste una sottosequenza comune, restituisce 0.

Una sequenza successiva di una stringa è una nuova stringa generata dalla stringa originale con alcuni caratteri (non può essere nessuno) eliminati senza modificare l'ordine relativo dei caratteri rimanenti. (Ad esempio, "asso" è una sottosequenza di "abcde").

Scrivi una funzione longestCommonSubsequence(text1: str, text2: str) -> int.

Vincoli
  • 1 <= len(text1), len(text2) <= 1000
  • text1 and text2 consist of only lowercase English characters

Esempi

Example 1
Input
text1 = "abcde", text2 = "ace"
Output
3
Explanation

The longest common subsequence is "ace" and its length is 3.

Example 2
Input
text1 = "abc", text2 = "abc"
Output
3
Explanation

The longest common subsequence is "abc" and its length is 3.

Example 3
Input
text1 = "abc", text2 = "def"
Output
0
Explanation

There is no common subsequence, so the result is 0.

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.