비어 있지 않은 문자열 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