JavaScript中迴圈字串中的唯一子字串


問題

假設我們有一個S,str.,它是一個字串的無限環繞字串——

"abcdefghijklmnopqrstuvwxyz".

因此,S將如下所示——

"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".

我們需要編寫一個JavaScript函式來獲取str,我們稱之為字串str,作為唯一的引數。

  • 我們的函式應該找出在S中存在多少個str的唯一且非空子字串。

  • 我們的函式最終應該返回字串S中str的不同非空子字串的數量。

例如,如果輸入函式為——

const str = "zab";

那麼輸出應該是——

const output = 6;

輸出說明

字串“zab”在字串S中有六個子字串“z”、“a”、“b”、“za”、“ab”、“zab”。

示例

此程式碼將為——

 即時演示

const str = "zab";
const allSubstrings = (str = '') => {
   const dp = new Array(26).fill(0);
   dp[str.charCodeAt(0) - 97] = 1;
   maxCount = 1;
   for (let i = 1; i < str.length; i++) {
      if ((str.charCodeAt(i) - str.charCodeAt(i - 1) == 1) || (str.charCodeAt(i) - str.charCodeAt(i - 1) == -25)) {
         maxCount++;
      } else {
         maxCount = 1;
      }
      dp[str.charCodeAt(i) - 97] = Math.max(dp[str.charCodeAt(i) - 97], maxCount);
   }
   return dp.reduce((item, val) => {
      return val + item;
   })
};
console.log(allSubstrings(str));

輸出

控制檯中的輸出將是——

6

更新日期:04-Mar-2021

145次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.