Difficile 2 risolte 66.7% di accettazione

Word Break

Decide whether text can be split into dictionary words.

Cosa imparerai

  • Mark which prefixes can be split
  • Use a set for fast dictionary lookups
  • Build a boolean DP over positions

Problema

Mostra traduzione

Decide whether text can be split into a sequence of words from words. Words may be reused. Dynamic programming over prefixes solves it efficiently.

Implement can_break(text, words).

Input

text: Lowercase letters only. words: The dictionary; each word has 1–50 lowercase letters.

Output

Return true if a split exists.

Vincoli

0 ≤ length of text ≤ 5,000; 1 ≤ words ≤ 1,000

Esempi

Esempio 1
Input:
text = "applepenapple"
words = ["apple", "pen"]

Output atteso:
expected = True
Input:
std::string text = "applepenapple";
std::vector<std::string> words = {"apple", "pen"};

Output atteso:
bool expected = true;
Input:
string text = "applepenapple";
string[] words = new string[] {"apple", "pen"};

Output atteso:
bool expected = true;

Spiegazione

"apple" + "pen" + "apple", reusing "apple".

Esempio 2
Input:
text = "catsandog"
words = ["cats", "dog", "sand", "and", "cat"]

Output atteso:
expected = False
Input:
std::string text = "catsandog";
std::vector<std::string> words = {"cats", "dog", "sand", "and", "cat"};

Output atteso:
bool expected = false;
Input:
string text = "catsandog";
string[] words = new string[] {"cats", "dog", "sand", "and", "cat"};

Output atteso:
bool expected = false;

Spiegazione

Every split leaves "og" or "ando" unmatched: false.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

A prefix is breakable if some earlier breakable point reaches it with a dictionary word.

Suggerimento 2

Dynamic programming over positions works well when you test word lengths or dictionary matches efficiently.

Suggerimento 3

Empty text is trivially breakable, but repeated word reuse should remain allowed throughout the scan.

Complessità attesa

O(n^2) time, O(n) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 806 ms - 5/5 Vedi il codice
2 KKKaneki Ken Python 851 ms - 2/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 2 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.