問題
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.
制約
0 ≤ length of text ≤ 5,000; 1 ≤ words ≤ 1,000
例
入力:
text = "applepenapple"
words = ["apple", "pen"]
期待される出力:
expected = True
入力:
std::string text = "applepenapple";
std::vector<std::string> words = {"apple", "pen"};
期待される出力:
bool expected = true;
入力:
string text = "applepenapple";
string[] words = new string[] {"apple", "pen"};
期待される出力:
bool expected = true;
解説
"apple" + "pen" + "apple", reusing "apple".
入力:
text = "catsandog"
words = ["cats", "dog", "sand", "and", "cat"]
期待される出力:
expected = False
入力:
std::string text = "catsandog";
std::vector<std::string> words = {"cats", "dog", "sand", "and", "cat"};
期待される出力:
bool expected = false;
入力:
string text = "catsandog";
string[] words = new string[] {"cats", "dog", "sand", "and", "cat"};
期待される出力:
bool expected = false;
解説
Every split leaves "og" or "ando" unmatched: false.
解き方のヒント
まずは自分で考えてから、ヒントを1つずつ開いてみましょう。
ヒント 1
A prefix is breakable if some earlier breakable point reaches it with a dictionary word.
ヒント 2
Dynamic programming over positions works well when you test word lengths or dictionary matches efficiently.
ヒント 3
Empty text is trivially breakable, but repeated word reuse should remain allowed throughout the scan.
目安の計算量
O(n^2) time, O(n) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。