Cho chuỗi str không rỗng và mảng từ arr. Xác định str có thể phân đoạn thành chuỗi các từ trong arr (cách nhau bởi khoảng trắng) hay không.
Lưu ý: Từ trong arr có thể dùng lại nhiều lần. Arr không chứa từ trùng.
Ví dụ: "applepenapple", ["apple", "pen"] → true ("apple pen apple").
Ví dụ
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));Kết quả
Kết quả in ra console:
true