โจทย์
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
prefix จะ break ได้ก็ต่อเมื่อมีจุดก่อนหน้าที่ break ได้แล้วและต่อด้วยคำใน dictionary
คำใบ้ 2
ใช้ dynamic programming บนตำแหน่งได้ผลดี ถ้าทดสอบความยาวคำหรือ match กับ dictionary อย่างมีประสิทธิภาพ
คำใบ้ 3
ข้อความว่างถือว่า break ได้ทันที แต่ควรอนุญาตให้ใช้คำเดิมซ้ำได้ตลอดการสแกน
ความซับซ้อนที่คาดหวัง
เวลา O(n^2), หน่วยความจำเพิ่ม O(n)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน