Khó 2 người đã giải Tỷ lệ chấp nhận 66.7%

Word Break

Decide whether text can be split into dictionary words.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
text = "applepenapple"
words = ["apple", "pen"]

Kết quả mong đợi:
expected = True
Đầu vào:
std::string text = "applepenapple";
std::vector<std::string> words = {"apple", "pen"};

Kết quả mong đợi:
bool expected = true;
Đầu vào:
string text = "applepenapple";
string[] words = new string[] {"apple", "pen"};

Kết quả mong đợi:
bool expected = true;

Giải thích

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

Ví dụ 2
Đầu vào:
text = "catsandog"
words = ["cats", "dog", "sand", "and", "cat"]

Kết quả mong đợi:
expected = False
Đầu vào:
std::string text = "catsandog";
std::vector<std::string> words = {"cats", "dog", "sand", "and", "cat"};

Kết quả mong đợi:
bool expected = false;
Đầu vào:
string text = "catsandog";
string[] words = new string[] {"cats", "dog", "sand", "and", "cat"};

Kết quả mong đợi:
bool expected = false;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

A prefix is breakable if some earlier breakable point reaches it with a dictionary word.

Gợi ý 2

Dynamic programming over positions works well when you test word lengths or dictionary matches efficiently.

Gợi ý 3

Empty text is trivially breakable, but repeated word reuse should remain allowed throughout the scan.

Độ phức tạp mong đợi

O(n^2) time, O(n) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 Н"Никита "Programmer" Python 806 ms - 5/5 Xem code
2 KKKaneki Ken Python 851 ms - 2/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 2 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.