Hard 0 solved 0% acceptance

Word Break

Decide whether text can be split into dictionary words.

Problem

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.

Constraints

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

Examples

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

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

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

Expected output:
bool expected = true;

Explanation

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

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

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

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

Expected output:
bool expected = false;

Explanation

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

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.