給出一個(gè)數(shù)組['heloo', 'helo', 'lofthe']
,期望得到每個(gè)數(shù)組元素中出現(xiàn)頻次最多且長(zhǎng)度最長(zhǎng)的字符串,如['lo', 'he']
,大家有沒(méi)有更便捷的解法
function test() {
// 我的思路是:從originList中找到最短的str,將當(dāng)前的字符串都排列組合一下模蜡,生成一個(gè)排列組合列表,遍歷這個(gè)排列組合列表扁凛,去整個(gè)originList中匹配忍疾,如果當(dāng)前的排列組合項(xiàng)在originList的每一項(xiàng)都能找到,就先將當(dāng)前的排列組合項(xiàng)放進(jìn)結(jié)果列表中谨朝,直到整個(gè)排列組合遍歷完卤妒,讀取結(jié)果列表中字符串長(zhǎng)度最長(zhǎng)的項(xiàng)
const originList = ["heloo", "helo", "lofthe"];
// 按字符串長(zhǎng)度從小到大排序
const newList = originList.sort((a, b) => a.length - b.length);
console.log(newList);
// 取得長(zhǎng)度最小的字符串
const str = newList[0];
// 將當(dāng)前字符串分割
const list = str.split("");
const arr = [];
// 遍歷分割的字符串,進(jìn)行排列組合字币,得到所有會(huì)出現(xiàn)的字符串組合
for (let index = 0; index < list.length; index++) {
let i = index;
let s = "";
while (i < list.length) {
s = `${s}${list[i]}`;
arr.push(s);
i++;
}
}
console.log(arr);
// 過(guò)濾出除了用于排列組合字符串之外的其它字符串集合
const otherList = newList.filter((item) => item !== str);
// 篩選出在所有字符串中均出現(xiàn)的排列組合
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);
// 避免出現(xiàn)長(zhǎng)度一樣的排列組合则披,所以使用數(shù)組
const res = newResult.filter(
(item) => item.length === newResult[0].length
);
console.log(newResult, res);
};
test();