เราได้รับ str สตริงที่ไม่ว่างเปล่าและอาร์เรย์ของสตริง arr ที่มีรายการคำที่ไม่ว่างเปล่า
เราจำเป็นต้องเขียนฟังก์ชันที่กำหนดว่า str สามารถแบ่งกลุ่มเป็นลำดับที่คั่นด้วยช่องว่างของคำตั้งแต่หนึ่งคำขึ้นไปในอาร์เรย์ได้หรือไม่
หมายเหตุ
-
คำเดียวกันในอาร์เรย์อาจถูกนำมาใช้ซ้ำหลายครั้งในการแบ่งกลุ่ม
-
อาร์เรย์ไม่มีคำซ้ำกัน
ตัวอย่างที่ 1
หากอินพุตเป็น
const str = "applepenapple"; const arr = ["apple", "pen"];
ผลลัพธ์ควรเป็นจริงเพราะ
"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