問題
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
ある位置までが分割可能なのは、そこに届く前の分割可能な位置から辞書の単語でつながる場合です。
ヒント 2
位置ごとの動的計画法は、単語長や辞書照合を効率よく試せると有効です。
ヒント 3
空文字列は自明に分割可能ですが、同じ単語の再利用は走査中ずっと許可してよいです。
目安の計算量
時間 O(n^2)、追加メモリ O(n)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。