JavaScript中循环字符串中的唯一子字符串

问题

假设我们有一个S,str。这是字符串的无限环绕字符串-

"abcdefghijklmnopqrstuvwxyz".

因此,S看起来像这样-

"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".

我们需要编写一个带str的JavaScript函数,我们将字符串str作为唯一参数。

  • 我们的函数应该找出S中有多少个唯一的非空子字符串str。

  • 我们的函数最终应该返回字符串S中str的不同非空子字符串的数量。

例如,如果函数的输入为-

const str = "zab";

那么输出应该是-

const output = 6;

输出说明

字符串S中有字符串“ zab”的六个子字符串“ 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