問題
text を words に含まれる単語の並びに分割できるかどうかを判定してください。同じ単語は何度使ってもかまいません。接頭辞に対する動的計画法を使うと効率よく解けます。
can_break(text, words) を実装してください。
入力
text: 英小文字のみからなります。 words: 辞書です。各単語は 1 から 50 文字の英小文字です。
出力
分割できる場合は true を返してください。
制約
0 ≤ text の長さ ≤ 5,000; 1 ≤ 単語数 ≤ 1,000
例
例 1
入力:
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" と、"apple" を再利用して分割できます。
例 2
入力:
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;
解説
どのように分割しても "og" か "ando" が辞書と一致せずに残ります。答えは false です。
解き方のヒント
まずは自分で考えてから、ヒントを1つずつ開いてみましょう。
ヒント 1
ある位置までが分割可能なのは、そこに届く前の分割可能な位置から辞書の単語でつながる場合です。
ヒント 2
位置ごとの動的計画法は、単語長や辞書照合を効率よく試せると有効です。
ヒント 3
空文字列は自明に分割可能ですが、同じ単語の再利用は走査中ずっと許可してよいです。
目安の計算量
時間 O(n^2)、追加メモリ O(n)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。