Difficile 0 risolte 0% di accettazione

Word Break

Decide whether text can be split into dictionary words.

Cosa imparerai

  • Segnare quali prefissi si possono dividere
  • Usare un insieme per ricerche veloci nel dizionario
  • Costruire una DP booleana sulle posizioni

Problema

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

Un prefisso è segmentabile se un punto di rottura precedente, già segmentabile, lo raggiunge con una parola del dizionario.

Suggerimento 2

La programmazione dinamica sulle posizioni funziona bene se testi in modo efficiente le lunghezze delle parole o i match nel dizionario.

Suggerimento 3

Il testo vuoto è banalmente segmentabile, ma il riuso ripetuto delle parole deve restare consentito per tutta la scansione.

Complessità attesa

tempo O(n^2), spazio aggiuntivo O(n)

Riferimenti

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

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.