เราได้รับสตริงที่ไม่ว่างเปล่า str และอาร์เรย์ของสตริง arr ที่มีรายการคำที่ไม่ว่างเปล่า
เราจำเป็นต้องเขียนฟังก์ชันที่กำหนดว่า str สามารถแบ่งเป็นลำดับคำคั่นด้วยช่องว่างได้หรือไม่ โดยคำทุกคำต้องมีอยู่ในอาร์เรย์
หมายเหตุ
- คำเดียวกันในอาร์เรย์อาจใช้ซ้ำได้หลายครั้งในการแบ่ง
- อาร์เรย์ไม่มีคำซ้ำ
ตัวอย่าง 1
ถ้าอินพุตคือ:
const str = "applepenapple"; const arr = ["apple", "pen"];
ผลลัพธ์ควรเป็น true เพราะ:
"applepenapple" can be segmented as "apple pen apple".
ตัวอย่างโค้ด
const str = "applepenapple";
const arr = ["apple", "pen"];
const wordSequence = (str = '', arr = []) => {
const map = {}
function helper(str) {
if (map.hasOwnProperty(str)) {
return map[str]
} else if (str=='') {
return true
}
for (let i=0;i<=str.length;i++) {
if (
arr.includes(str.slice(i)) &&
helper(str.slice(0, i))
){
map[str] = true
return true
}
};
map[str] = false;
return false;
};
return helper(str)
};
console.log(wordSequence(str, arr));
ผลลัพธ์
ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:
true