给出一个数组['heloo', 'helo', 'lofthe'],期望得到每个数组元素中出现频次最多且长度最长的字符串,如['lo', 'he']
function test() {
// 我的思路是:从originList中找到最短的str,将当前的字符串都排列组合一下,生成一个排列组合列表,遍历这个排列组合列表,去整个originList中匹配,如果当前的排列组合项在originList的每一项都能找到,就先将当前的排列组合项放进结果列表中,直到整个排列组合遍历完,读取结果列表中字符串长度最长的项
const originList = ["heloo", "helo", "lofthe"]
// 按字符串长度从小到大排序
const newList = originList.sort((a, b) => a.length - b.length)
console.log(newList)
// 取得长度最小的字符串
const str = newList[0]
// 将当前字符串分割
const list = str.split("")
const arr = []
// 遍历分割的字符串,进行排列组合,得到所有会出现的字符串组合
for (let index = 0
let i = index
let s = ""
while (i < list.length) {
s = `${s}${list[i]}`
arr.push(s)
i++
}
}
console.log(arr)
// 过滤出除了用于排列组合字符串之外的其它字符串集合
const otherList = newList.filter((item) => item !== str)
// 筛选出在所有字符串中均出现的排列组合
const result = []
arr.forEach((item) => {
if (otherList.every((str) => str.indexOf(item) !== -1)) {
result.push(item)
}
})
const newResult = result.sort((a, b) => b.length - a.length)
// 避免出现长度一样的排列组合,所以使用数组
const res = newResult.filter(
(item) => item.length === newResult[0].length
)
console.log(newResult, res)
}
test()