可以在JavaScript中对字符串进行分段吗
我们给了一个非空字符串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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短