Le migliori 150 intervisteMedio

Rottura di parole

Guida dettagliata e implementazione Python per il problema "Interruzione di parola".

Dichiarazione del problema

Medio

Data una stringa s e un dizionario di stringhe wordDict, restituisce True se s può essere segmentato in una sequenza separata da spazi di una o più parole del dizionario.

Tieni presente che la stessa parola nel dizionario può essere riutilizzata più volte nella segmentazione.

Scrivi una funzione wordBreak(s: str, wordDict: List[str]) -> bool.

Vincoli
  • 1 <= len(s) <= 300
  • 1 <= len(wordDict) <= 1000
  • 1 <= len(wordDict[i]) <= 20
  • s and wordDict[i] consist of only lowercase English letters
  • All the strings of wordDict are unique

Esempi

Example 1
Input
s = "leetcode", wordDict = ["leet","code"]
Output
True
Explanation

Return True because "leetcode" can be segmented as "leet code".

Example 2
Input
s = "applepenapple", wordDict = ["apple","pen"]
Output
True
Explanation

Return True because "applepenapple" can be segmented as "apple pen apple".

Example 3
Input
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output
False
Explanation

No valid segmentation exists.

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