JavaScript中最長字串鏈的長度


單詞鏈

假設只有當我們可以精確地在word1中新增一個字母使其等於word2時,word1才是word2的前導詞。例如,“abc”是“abac”的前導詞。

單詞鏈是一個單詞序列[word_1, word_2, ..., word_k],其中k >= 1,word_1是word_2的前導詞,word_2是word_3的前導詞,以此類推。

問題

我們需要編寫一個JavaScript函式,該函式將字串陣列arr作為第一個也是唯一的引數。

陣列arr中的每個字串都由英文小寫字母組成。我們的函式應該返回從給定陣列arr中選擇的單詞的最長單詞鏈的可能長度。

例如,如果函式的輸入為:

const arr = ["a","b","ba","bca","bda","bdca"];

則輸出應為:

const output = 4;

輸出解釋

最長的單詞鏈之一是“a”、“ba”、“bda”、“bdca”。

示例

程式碼如下:

const arr = ["a","b","ba","bca","bda","bdca"];
const longestStrChain = (arr) => {
   arr.sort((a, b) => a.length - b.length);
   const isPredecessor = (word1 = '', word2 = '') => {
      if(Math.abs(word1.length - word2.length) !== 1){
         return false;
      };
      for(let i = 0; i < word2.length; i++){
         const word = word2.slice(0, i) + word2.slice(i + 1);
         if(word === word1){
            return true;
         };
      };
      return false;
   };
   const array = [];
   let max = 0;
   for(let i = arr.length - 1; i >= 0; i--){
      array[i] = 1;
      for(let j = arr.length - 1; j > i; j--){
         if(isPredecessor(arr[i], arr[j])){
            array[i] = Math.max(
               array[i],
               1 + array[j],
            );
         };
      };
      max = Math.max(max, array[i]);
   };
   return max;
};
console.log(longestStrChain(arr));

輸出

控制檯輸出:

4

更新於:2021年4月7日

320 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.