難しい 2件解決済み 正答率66.7%

Word Break

Decide whether text can be split into dictionary words.

このチャレンジで学べること

  • Mark which prefixes can be split
  • Use a set for fast dictionary lookups
  • Build a boolean DP over positions

問題

翻訳を表示

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

例

例 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", reusing "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;

解説

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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 806 ms - 5/5 コードを見る
2 KKKaneki Ken Python 851 ms - 2/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が2件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。