JavaScript 中包含兩個不同字元的最長字串


我們需要編寫一個 JavaScript 函式,它以字串作為第一個引數,以一個數字(小於字串長度)作為第二個引數。該函式應該從原始字串中刪除字元,並準備一個新字串,使其成為最長的字串,最多包含兩個不同的字元。

最後,該函式應返回所需字串的長度。

例如:如果輸入字串為 -

const str = 'kjeljsdl';

那麼輸出應為 -

const output = 4;

因為具有最多 2 個不同字元的最長子字串是 'jljl'

示例

程式碼如下 -

 線上演示

const str = 'kjeljsdl';
const longestSubstring = (str = '') => {
   const { length } = str;
   if (length <= 1){
      return 0;
   };
   const keys = [...new Set(str)];
   const arr = [];
   let max = 0;
   for (let i = 0; i < keys.length - 1; i++) {
      for (let j = i + 1; j < keys.length; j++) {
         arr.push(keys[i] + keys[j]);
      }
   }
   arr.forEach(item => {
      let sub = '';
      for (let i = 0; i < str.length; i++) {
         if (sub[sub.length - 1] === str[i]) {
            sub = '';
            break;
         }
         if (item.includes(str[i])) {
            sub += str[i];
         }
      }
      if (sub && sub.length > max){
         max = sub.length;
      };
   });
   return max;
}
console.log(longestSubstring(str));

輸出

控制檯中的輸出將為 -

4

更新於:2021-02-24

317 次瀏覽

開啟您的 職業

完成此課程以獲得認證

開始
廣告
© . All rights reserved.