在 JavaScript 中查詢陣列中最長的不常見子字串


子序列

出於此問題的目的,我們將子序列定義為可以透過刪除某些字元而無需更改剩餘元素順序從一個序列派生的序列。任何字串都是其自身的子序列,空字串是任何字串的子序列。

問題

我們需要編寫一個 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

更新於: 2021-03-03

152 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.