Problème
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.
Contraintes
0 ≤ length of text ≤ 5,000; 1 ≤ words ≤ 1,000
Exemples
Entrée :
text = "applepenapple"
words = ["apple", "pen"]
Sortie attendue :
expected = True
Entrée :
std::string text = "applepenapple";
std::vector<std::string> words = {"apple", "pen"};
Sortie attendue :
bool expected = true;
Entrée :
string text = "applepenapple";
string[] words = new string[] {"apple", "pen"};
Sortie attendue :
bool expected = true;
Explication
"apple" + "pen" + "apple", reusing "apple".
Entrée :
text = "catsandog"
words = ["cats", "dog", "sand", "and", "cat"]
Sortie attendue :
expected = False
Entrée :
std::string text = "catsandog";
std::vector<std::string> words = {"cats", "dog", "sand", "and", "cat"};
Sortie attendue :
bool expected = false;
Entrée :
string text = "catsandog";
string[] words = new string[] {"cats", "dog", "sand", "and", "cat"};
Sortie attendue :
bool expected = false;
Explication
Every split leaves "og" or "ando" unmatched: false.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Un préfixe est découpable si un point de découpe précédent atteint ce préfixe avec un mot du dictionnaire.
Indice 2
La programmation dynamique sur les positions fonctionne bien si tu testes efficacement les longueurs de mots ou les correspondances du dictionnaire.
Indice 3
Le texte vide est trivialement découpable, mais la réutilisation répétée des mots doit rester autorisée tout au long du parcours.
Complexité attendue
temps O(n^2), espace supplémentaire O(n)
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.