给定一个较长字符串
big
和一个包含较短字符串的数组smalls
,设计一个方法,根据smalls
中的每一个较短字符串,对big
进行搜索。输出smalls
中的字符串在big
里出现的所有位置positions
,其中positions[i]
为smalls[i]
出现的所有位置。示例:
输入: big = "mississippi" smalls = ["is","ppi","hi","sis","i","ssippi"] 输出: [[1,4],[8],[],[3],[1,4,7,10],[5]]提示:
0 <= len(big) <= 1000
0 <= len(smalls[i]) <= 1000
smalls
的总字符数不会超过 100000。- 你可以认为
smalls
中没有重复字符串。- 所有出现的字符均为英文小写字母。
/**
* @param {string} big
* @param {string[]} smalls
* @return {number[][]}
*/
function TreeNode(val){
this.val = val || null;
this.children = {};
}
var multiSearch = function(big, smalls) {
const res = smalls.map(() => []);
if(!big){
return res;
}
let Tree = new TreeNode();
let now;
smalls.forEach((small,index) =>{
now = Tree;
for(let i = 0;i < small.length;i++){
if(!now.children[small[i]]){
now.children[small[i]] = new TreeNode(small[i]);
}
now = now.children[small[i]];
}
now.children['last'] = index;
})
for(let i = 0;i < big.length;i++){
let now = Tree;
for(let j = i;i < big.length;j++){
if(!now.children[big[j]]){
break;
}
now = now.children[big[j]];
if(now.children.last !== undefined){
res[now.children.last].push(i)
}
}
}
return res;
};
标签:smalls,big,面试题,children,let,17.17,small,now,leetcode
From: https://blog.csdn.net/Turboyiyi/article/details/143855077