出于此问题的目的,我们将子序列定义为可通过删除一些字符而无需更改其余元素的顺序而从一个序列派生的序列。任何字符串都是其自身的子序列,而空字符串则是任何字符串的子序列。
我们需要编写一个JavaScript函数,该函数将字符串数组作为唯一参数。我们的函数需要找到其中最长的不常见子序列的长度。
最长的不常见子序列是指数组中一个字符串的最长子序列,该子序列不应是数组中其他字符串的任何子序列。
如果不存在不常见的子序列,则应返回-1。
例如,如果函数的输入为-
const arr = ["aba", "cdc", "eae"];
那么输出应该是-
const output = 3;
“ aba”,“ cdc”和“ eae”都是长度为3的有效罕见子序列。
为此的代码将是-
const arr = ["aba", "cdc", "eae"];
const longestUncommon = (strs) => {
const map = {};
const arr = [];
let max = -1;
let index = -1;
for(let i = 0; i < strs.length; i++){
map[strs[i]] = (map[strs[i]] || 0) + 1;
if(map[strs[i]] > 1){
if(max < strs[i].length){
max = strs[i].length
index = i;
}
}
}
if(index === -1) {
strs.forEach(el =>{
if(el.length > max) max = el.length;
})
return max;
}
for(let i = 0; i < strs.length; i++){
if(map[strs[i]] === 1) arr.push(strs[i]);
}
max = -1
for(let i =arr.length- 1; i >= 0; i--){
let l = arr[i];
let d = 0;
for(let j = 0; j < strs[index].length; j++){
if(strs[index][j] === l[d]){
d++;
}
}
if(d === l.length){
let temp = arr[i];
arr[i] = arr[arr.length - 1];
arr[arr.length - 1] = temp;
arr.pop();
}
}
arr.forEach(el =>{
if(el.length > max) max = el.length;
})
return max;
};
console.log(longestUncommon(arr));输出结果控制台中的输出将是-
3